使用boost :: mpl组合类型

raf*_*fak 4 c++ metaprogramming boost-mpl

我有一个类型列表,我想从中构建包含两个元素的所有组合的列表.例如:

namespace mpl = boost::mpl;
typedef mpl::vector<int, long> typelist;
// mpl magic...
// the wanted list is equivalent to:
typedef mpl::vector<pair<int, int>, pair<int, long>,
                    pair<long, int>, pair<long, long> > combinations;
Run Code Online (Sandbox Code Playgroud)

在这里,pair<T1,T2>可能是std::pair<T1,T2>,或mpl::vector<T1,T2>.这该怎么做?当我们考虑时,我也有兴趣删除重复项pair<T1, T2> == pair<T2, T1>.
谢谢.

hka*_*ser 6

可以通过调用以下方式计算单个类型int与类型列表的组合列表:mpl::vector<int, long>mpl::fold

typedef fold<
    mpl::vector<int, long>, vector<>, 
    push_back<mpl::_1, std::pair<int, mpl::_2> > 
>::type list_of_pairs;
Run Code Online (Sandbox Code Playgroud)

现在,如果我们将它包装到一个单独的元函数中并为所有类型的初始类型列表调用它,我们得到:

typedef mpl::vector<int, long> typelist;

template <typename T, typename Result>
struct list_of_pairs
  : mpl::fold<typelist, Result, 
        mpl::push_back<mpl::_1, std::pair<T, mpl::_2> > > 
{};

typedef mpl::fold<
    typelist, mpl::vector<>, mpl::lambda<list_of_pairs<mpl::_2, mpl::_1> >
>::type result_type;

BOOST_MPL_ASSERT(
    mpl::equal<result_type, 
        mpl::vector4<
            std::pair<int, int>, std::pair<int,long>,
            std::pair<long,int>, std::pair<long,long> 
        > >::value);
Run Code Online (Sandbox Code Playgroud)

编辑:回答第二个问题:

使结果只包含唯一元素(在您提到的意义上)更多涉及.首先,您需要定义一个比较两个元素并返回mpl :: true_/mpl :: false_的元函数:

template <typename P1, typename P2>
struct pairs_are_equal
  : mpl::or_<
        mpl::and_<
            is_same<typename P1::first_type, typename P2::first_type>,
            is_same<typename P1::second_type, typename P2::second_type> >,
        mpl::and_<
            is_same<typename P1::first_type, typename P2::second_type>, 
            is_same<typename P1::second_type, typename P2::first_type> > >
{};
Run Code Online (Sandbox Code Playgroud)

然后我们需要定义一个元函数,它试图找到给定列表中的给定元素:

template <typename List, typename T>
struct list_doesnt_have_element
  : is_same<
        typename mpl::find_if<List, pairs_are_equal<mpl::_1, T> >::type, 
        typename mpl::end<List>::type>
{};
Run Code Online (Sandbox Code Playgroud)

现在,这可用于构建新列表,确保不插入重复项:

typedef mpl::fold<
    result_type, mpl::vector<>,
    mpl::if_<
        mpl::lambda<list_doesnt_have_element<mpl::_1, mpl::_2> >, 
        mpl::push_back<mpl::_1, mpl::_2>, mpl::_1>

>::type unique_result_type;
Run Code Online (Sandbox Code Playgroud)

所有这一切都来自我的头脑,因此可能需要在这里或那里进行一些调整.但这个想法应该是正确的.


编辑:@rafak概述的小修正