我使用以下构造来创建类型的mpl vector 。
struct Struct1{
typedef int type;
};
struct Struct2{
typedef float type;
};
template<typename T> struct TypeReader{
typedef typename T::type type;
};
int main()
{
typedef bm::vector<Struct1,Struct2> MPLVector;
typedef bm::transform<MPLVector, TypeReader<bm::_1>>::type TypeList;
static_assert(bm::equal<TypeList, bm::vector<int,float> >::value, "Is not same");
}
到目前为止,这可以按预期进行。现在我想做的是以下
struct Struct3{
typedef bm::vector<char,double> type;
};
typedef bm::vector<Struct1,Struct2,Struct3> MPLVector;
typedef bm::transform<MPLVector, TypeReader<bm::_1>>::type TypeList;
static_assert(bm::equal<TypeList, bm::vector<int,float,char,double> >::value, "Is not same");
这是行不通的。那么,我该如何更改我的MetaFunction结构,使其可以同时使用typedef和mpl::vector?
还是如果这不可能,如果我将所有typedef更改为mpl vector,是否可以这样做?
最佳答案
我认为mpl::transform
不可能做到这一点,因为它需要从源序列中的单个元素生成结果序列中的多个元素。但是,可以使用 mpl::fold
以及 mpl::is_sequence
进行专门化:
// Default case
template < typename Seq, typename TWrapper, typename Enable = void >
struct Flatten_imp
: mpl::push_back< Seq, typename TWrapper::type >
{
};
// Sequence case
template < typename Seq, typename TWrapper >
struct Flatten_imp<
Seq,
TWrapper, typename
boost::enable_if<
mpl::is_sequence< typename
TWrapper::type
>
>::type
>
{
typedef mpl::joint_view<
Seq, typename
TWrapper::type
> type;
};
template < typename Seq >
struct Flatten
: mpl::fold< Seq, mpl::vector<>, Flatten_imp< mpl::_, mpl::_ > >
{}
int main()
{
typedef mpl::vector< Struct1, Struct2, Struct3 > MPLVector;
typedef Flatten< MPLVector >::type TypeList;
static_assert(
mpl::equal<
TypeList,
mpl::vector< int, float, char, double >
>::value, "Is not same");
}
如果您希望展平是递归的,则可以在附加序列之前调用
Flatten
中的Flatten_impl
展平该序列。但是请注意,只有当您的序列包含包装器而不包含直接类型(例如struct Struct3
{
typedef mpl::vector< mpl::identity< char >, mpl::identity< double > > type;
}
关于c++ - 如何将type和mpl::vector连接到新 vector 中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7926776/