【问题标题】:Boost MPL nested lambdasBoost MPL 嵌套 lambda
【发布时间】:2013-04-18 16:02:13
【问题描述】:

我一直在努力掌握Boost MPL

作为简单的练习,我试过了:

typedef vector_c<int, 1, 2, 3, 4, 5>::type example_list;

typedef transform<example_list, times<_, int_<2> > >::type doubled_example_list;

typedef transform<example_list, negate<_> >::type negated_example_list;

BOOST_STATIC_ASSERT((at_c<negated_example_list, 2>::type::value==-3));
BOOST_STATIC_ASSERT((at_c<doubled_example_list, 4>::type::value==10));

这些都可以正常工作。但是,以下尝试无法编译:

typedef transform<_, negate<_> > negate_a_list;

typedef apply<negate_a_list, example_list>::type negated_example_list_2;

BOOST_STATIC_ASSERT((at_c<negated_example_list_2, 2>::type::value==-3));

我认为这与negate_a_list 中占位符的范围有关,但是我不确定如何解决它。有任何想法吗?我还怀疑我对 MPL 的语法和语义的一些假设是有缺陷的。我将不胜感激有关探索 MPL 的任何提示。

附:以下是上述代码的序言:

#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/static_assert.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/times.hpp>
#include <boost/mpl/size_t.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/mpl/lambda.hpp>
#include <boost/mpl/negate.hpp>
#include <boost/mpl/at.hpp>

using namespace boost::mpl;
using namespace boost::mpl::placeholders;

【问题讨论】:

  • 问题是占位符是指两个不同层次的应用:调用apply时需要绑定第一个,调用transform时必须绑定第二个。在您的代码中,negate_a_list 是二进制元函数,而它应该是返回一元元函数的一元元函数。处理嵌套的 lambda 表达式可能会很棘手,您可以在 this thread on the Boost mailing list 中找到一些答案。
  • 勘误:negate_a_list 不应该真的“返回一元元函数”,而是某种封装。基本上,你现在拥有的类似于这个 lambda (x, y) =&gt; transform(x, negate(y)),而你需要 (x) =&gt; transform(x, (y) =&gt; negate(y))

标签: c++ boost-mpl


【解决方案1】:

感谢 Luc Touraille 对我的问题的评论,Boost 邮件列表提供了the answer。此代码有效:

typedef transform<_, lambda<negate<_> >::type > negate_a_list;

typedef apply<negate_a_list, example_list>::type negated_example_list_2;

BOOST_STATIC_ASSERT((at_c<negated_example_list_2, 2>::type::value==-3));

注意在 lambda 表达式周围添加了 lambda&lt;...&gt;::type。这足以限制占位符的范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    相关资源
    最近更新 更多