【问题标题】:How can I implement nested boost::mpl::fold如何实现嵌套的 boost::mpl::fold
【发布时间】:2015-06-12 10:40:00
【问题描述】:

如何实现嵌套 boost::mpl::fold ?

namespace mpl=boost::mpl;

typedef mpl::vector_c<int,1,1,1> vec1;
typedef mpl::vector_c<int,2,2,2> vec2;
typedef mpl::vector_c<int,3,3,3> vec3;
typedef mpl::vector<vec1,vec2,vec3> vvec;

typedef typename mpl::lambda
    <mpl::fold
        <mpl::_1
        ,mpl::int_<0>
        ,typename mpl::lambda<mpl::plus<mpl::_1,mpl::_2>>::type
        >
    >::type lam;

typedef typename mpl::fold
    <vvec
    ,mpl::int_<0>
    ,mpl::plus<mpl::_1,typename lam::template apply<mpl::_2>::type>
    >::type result;

BOOST_MPL_ASSERT((mpl::equal_to<result,mpl::int_<18>>));

我希望结果为 18,但大于等于 0。

【问题讨论】:

    标签: c++ boost boost-mpl


    【解决方案1】:

    嵌套绑定总是会引起占位符之间的冲突:lambda 使用与外部折叠相同的占位符,而替换会做错事。

    Boost Lambda、Boost Bind 和是的,甚至 Boost Mpl 都实现了 protect/unprotect 组合,因此您可以解决此问题:

    Live On Coliru

    #include <boost/mpl/vector.hpp>
    #include <boost/mpl/vector_c.hpp>
    #include <boost/mpl/fold.hpp>
    #include <boost/mpl/lambda.hpp>
    #include <boost/mpl/plus.hpp>
    #include <boost/mpl/int.hpp>
    #include <boost/mpl/assert.hpp>
    #include <boost/mpl/protect.hpp>
    #include <boost/mpl/equal_to.hpp>
    
    namespace mpl = boost::mpl;
    
    typedef mpl::vector_c<int, 1, 1, 1> vec1;
    typedef mpl::vector_c<int, 2, 2, 2> vec2;
    typedef mpl::vector_c<int, 3, 3, 3> vec3;
    typedef mpl::vector<vec1, vec2, vec3> vvec;
    
    typedef typename mpl::lambda<
            mpl::fold<
                mpl::_1, 
                mpl::int_<0>, 
                typename mpl::lambda<mpl::plus<mpl::_1, mpl::_2> >::type
            >
        >::type lam;
    
    typedef typename mpl::fold<
            vvec, 
            mpl::int_<0>, 
            mpl::plus<mpl::_1, mpl::protect<lam>::type::apply<mpl::_2> >
        >::type result;
    
    static_assert(mpl::equal_to<result, mpl::int_<18>>::value, "should be 18");
    
    int main() {}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多