【问题标题】:Boost Fusion/MPL: convert type from sequence to sequence of equivalent any_range'sBoost Fusion / MPL:将类型从序列转换为等效any_range的序列
【发布时间】:2011-03-30 08:40:25
【问题描述】:

我想使用 Boost 的any_range 来处理多个异构数据范围。我的数据范围的类型称为融合向量,例如:

typedef vector<double, int, char> TypeSequence

给定这样的类型,我想编写一个模板来派生出这样的进一步类型:

vector<AnyRange<double>::value, AnyRange<int>::value, AnyRange<char>::value>

其中AnyRange 定义为:

using namespace boost;
template <typename T>
struct AnyRange
{
    typedef typename any_range<typename T, forward_pass_traversal_tag, int, std::ptrdiff_t> value;
};

我尝试过但失败了。这甚至可以通过 Fusion 实现吗? MPL?或者也许我用any_range 走错了路。

【问题讨论】:

  • 这绝对是可能的——但是,看起来您更想将 MPL 向量(一个没有实际数据的向量)转换为一个融合向量(一个有数据的向量)。另外,您对“typename”的使用看起来有点不对...

标签: c++ templates boost boost-mpl boost-fusion


【解决方案1】:

您可以使用 boost::mpl::transform 轻松完成此操作,您可以将其与 Fusion 序列一起使用(只要您包含适当的标头以使 Fusion 序列表现为确认 MPL 序列):

#include <boost/range/any_range.hpp>

#include <boost/fusion/include/mpl.hpp> // Required to adapt Fusion to MPL
#include <boost/fusion/include/vector.hpp>

#include <boost/mpl/transform.hpp>


template < typename T >
struct EmbedInAnyRange
{
    typedef boost::any_range< // no need for typename here
        T,                    // no need for typename here
        forward_pass_traversal_tag, 
        int,                  // not sure what this parameter is, I leave int...
        std::ptrdiff_t
    > type;
};

int main()
{
    typedef boost::fusion::vector< double, int, char > Tuple;

    typedef boost::mpl::transform<
        Tuple,
        EmbedInAnyRange< boost::mpl::_ >
    >::type AnyRangeTuple;

    AnyRangeTuple myTuple( 
        std::vector< double >(), 
        std::list< int >(), 
        std::vector< char >() );
}

如果你愿意,你可以把转换放到它自己的元函数中:

template < typename Seq >
struct EmbedAllInAnyRange
{
    typedef typename boost::mpl::transform< // typename needed
        Seq,
        EmbedInAnyRange< boost::mpl::_ >
    >::type type;
};

...

typedef EmbedAllInRange< Tuple >::type AnyRangeTuple;

【讨论】:

  • 值得注意的是这里需要#include &lt;boost/fusion/mpl.hpp&gt;(或.../include/mpl.hpp)。与文档相反,boost 融合序列不会自动成为 MPL 序列,至少在不包含此头文件的情况下不会。未能包含此标头可能会导致一些非常晦涩(即使对于 MPL)的错误消息。
  • @Luc Touraille:我只能确认@Alastair 在这里写了什么,因此建议对包含&lt;boost/fusion/include/mpl.hpp&gt; 的大注释进行编辑。刚刚遇到了这个问题,出现了非常奇怪的错误消息:error: implicit instantiation of undefined template 'boost::mpl::clear_impl&lt;boost::fusion::fusion_sequence_tag&gt;::apply&lt;boost::fusion::vector&lt;...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-29
相关资源
最近更新 更多