如何将boost :: mpl :: vector转换为另一个boost :: mpl :: vector?

时间:2017-02-06 14:45:25

标签: c++ templates

假设我有一个boost::mpl::vector" myvec",例如这样定义:

using myvec = boost::mpl::vector<int, double, double>;

现在我想定义另一个类型myvecex,它使用添加的字符串将每个myvec成员转换为std::tuple。我想得到一个这样定义的类型:

using myvecex = boost::mpl::vector<std::tuple<int, std::string>, 
                                   std::tuple<double, std::string>,
                                   std::tuple<double, std::string> >;

但我不想重复自己并命名所有的矢量成员。相反,我想定义some_smart_template模板类型,我将以某种方式将每个成员类型转换为元组的逻辑。

using myvecex2 = some_smart_template<myvec>; 
static_assert(std::is_same<myvecex, myvecex2>::value);

它在C ++中是否可行?

1 个答案:

答案 0 :(得分:1)

Boost.MPL不只是为您提供容器,它还为您提供了这些容器的算法。在这种情况下,您想要的是transform

template<
      typename Sequence
    , typename Op
    , typename In = unspecified
    >
struct transform
{
    typedef unspecified type;
};

语义是你给它一个序列和MPL所指的Lambda Expression,你得到另一个序列。具体做法是:

using B = mpl::transform<A,
    std::tuple<mpl::_1, std::string>
    >::type;

或者至少在apply支持变量类模板(如std::tuple)时可以使用。所以你需要编写一个元函数类的操作:

struct tuple_of_strings {
    template <class T>
    struct apply {
        using type = std::tuple<T, std::string>;
    };
};

using B = mpl::transform<A, tuple_of_strings>::type;

或元函数:

template <class T>
struct tuple_of_strings {
    using type = std::tuple<T, std::string>;
};

using B = mpl::transform<A, tuple_of_strings<_1>>::type;