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

How to transform boost::mpl::vector into another boost::mpl::vector?

本文关键字:vector boost mpl 另一个 转换      更新时间:2023-10-16

假设我有一个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++中可行吗?

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

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

语义是你给它一个序列,MPL称之为Lambda表达式,然后你得到另一个序列。具体说来:

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;
相关文章: