如何在折叠过程中获取成员类型的提升::mpl 占位符

How to get member type of boost::mpl placeholders during fold

本文关键字:类型 mpl 占位符 成员类 折叠 过程中 成员 获取      更新时间:2023-10-16

假设有两个类:

struct A
{
    using Key = int;
    using Value = char;
};
struct B
{
    using Key = char;
    using Value = float;
};

我想使用它们的成员类型来定义融合映射:

typedef boost::fusion::map
<
    boost::fusion::pair< int , char > ,
    boost::fusion::pair< char , float >
> desired_type;

所以我决定使用 MPL 折叠来获取类型:

typedef boost::fusion::result_of::as_map< boost::mpl::fold
<
    boost::mpl::vector< A , B > ,
    boost::fusion::map< > ,
    boost::fusion::result_of::push_back
    <
        boost::mpl::_1 ,
        boost::fusion::result_of::make_pair
        <
            boost::mpl::_2 ::Key , boost::mpl::_2 ::Value
        >
    >
>::type >::type map_type;

但这当然行不通,因为boost::mpl::_N实际上是返回第 N 个参数的元函数。

因此,我定义了两个辅助元函数:

template< class T >
struct GetInnerKey
{
    typedef typename T::Key type;
};
template< class T >
struct GetInnerValue
{
    typedef typename T::Value type;
};

并正确定义了折叠:

typedef boost::fusion::result_of::as_map< boost::mpl::fold
<
    boost::mpl::vector< A , B > ,
    boost::fusion::map< > ,
    boost::fusion::result_of::push_back
    <
        boost::mpl::_1 ,
        boost::fusion::result_of::make_pair
        <
            GetInnerKey< boost::mpl::_2 > , GetInnerValue< boost::mpl::_2 >
        >
    >
>::type >::type map_type;

(住在科利鲁)

我的问题是:

  • 有没有办法摆脱GetInnerKey< >并使用MPL或Fusion中已经定义的东西来GetInnerValue< >

  • 有没有办法避免使用boost::fusion::result_of::as_map< >

  • 这是实现我的意图的正确方法吗?

占位符是元函数,应与惰性求值一起使用。占位符 _1 和 _2 中的 ::types 是评估前的一些复杂类型(您可以通过 typeof (使用 g++)检查它们)。

由于类 A 和 B 不是元函数

,所以你可能必须编写元函数来处理与类 A 和 B 的交互。

例如

template <class PT1, class... PTs>
struct map_type
{
    typedef typename map_type<PTs...>::type pts_map;
    typedef typename boost::fusion::result_of::as_map<
        boost::fusion::joint_view<
            boost::fusion::map<
                boost::fusion::pair< typename PT1::Key, typename PT1::Value>
            >,
            pts_map
        >
    >::type type;
};
template <class PT1>
struct map_type<PT1>
{
    typedef boost::fusion::map<
        boost::fusion::pair< typename PT1::Key, typename PT1::Value>
    > type;
};

住在科里鲁