我有一个包含多种类型的boost::mpl::vector
,例如
typedef boost::mpl::vector<T1, T2, T3, T4> list_type;
对于某些已知类型T1, T2, T3, T4
.有没有办法使用元编程将此列表转换为表示直接线性继承的类型,按向量中的类型顺序排列?我想合成一个具有与此一致的行为的类型:
struct T1 { };
struct T2 : T1 { };
struct T3 : T2 { };
struct T4 : T3 { };
struct synthesized_type : T4 { };
有一些boost::mpl::inherit_linearly
给了我类似的行为,但不完全是我想要的。使用 生成的类型的行为更像:
struct synthesized_type : T1, T2, T3, T4 { };
在某些情况下表现不同。例如,假设您有一个函数在T1, T2, T3, T4
类型的某个子集上重载:
void foo(T1) { }
void foo(T3) { }
foo(synthesized_type()); // I would like to be able to do this
使用我上面给出的第一个(所需的)层次结构,过载解决没有歧义;我可以将synthesized_type
传递给foo()
,它会调用foo(T3)
,因为T3
是synthesized_type
祖先中最派生的类型。
但是,在我使用boost::mpl::inherit_linearly
的情况下,由于重载解析的歧义,这会导致编译器错误,因为在父类型之间没有指定优先级;编译器无法在foo(T1)
和foo(T3)
之间进行选择。
有什么方法可以得到我想要的效果吗?更正式地陈述:
给定一个类型列表,我想使用元编程来合成具有我上面描述的第一个层次结构属性的某种类型(即,合成类型隐式转换为每个类型
T1, T2, T3, T4
,优先级按该顺序排列,因此T4
优先于T3
,后者优先于T2
, 等等)。这可能吗?
如果你的类型都是CRTP类型,你可以做这个巫术:
#include <iostream>
template< template<class> class... Ts >
struct TVec { };
struct EmptyClass { };
template< class T >
struct Inheritor;
template< template<template<class> class> class U, template<class> class T>
struct Inheritor< U<T> >
: public T<EmptyClass> { };
template< template<template<class> class...> class U, template<class> class T, template<class> class... Ts>
struct Inheritor< U<T, Ts... > >
: public T<Inheritor< U<Ts...> > > { } ;
template< typename Base >
struct T1
: public Base { };
template< typename Base >
struct T2
: public Base { };
template< typename Base >
struct T3
: public Base { };
template<typename X>
void foo(T1<X> t) {
std::cout << "T1" << std::endl;
}
template<typename X>
void foo(T2<X> t) {
std::cout << "T2" << std::endl;
}
template<typename X>
void foo(T3<X> t) {
std::cout << "T3" << std::endl;
}
int main() {
using Types = TVec< T1, T2, T3 >;
using Types2 = TVec< T3, T2, T1 >;
using Derived = Inheritor<Types>;
using Derived2 = Inheritor<Types2>;
//Inheritor<TVec< T1, T2, T3>> x;
Derived x;
Derived2 x2;
foo(x); // T1 overload
foo(x2); // T3 overload
}
template< class T >
struct Inheritor { };
template< class T, template<class> class U >
struct Inheritor< U<T> >
: public T { };
template< template<class...> class U, class T, class... Ts >
struct Inheritor< U<T, Ts...> >
: public T
, public Inheritor< U< Ts... > > { };