2013-04-18 52 views
7

我一直试图去与Boost MPL交手。Boost MPL嵌套lambdas

作为简单的练习,我想:

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的提示。

P.S.下面是上面的代码的序言:

#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; 
+2

问题是占位符引用了两个不同级别的应用程序:第一个在调用'apply'时需要绑定,而第二个在调用'transform'时必须绑定。在你的代码中,'negate_a_list'是一个二元函数,它应该是一元函数,返回一元函数。处理嵌套lambdas可能会很棘手,您可以在[Boost邮件列表中的此线程](http://lists.boost.org/Archives/boost/2012/01/189614.php)中找到一些答案。 –

+0

错误:'negate_a_list'不应该真的“返回一元函数”,它只是一种封装。基本上,当你需要'(x)=> transform(x,(y)=> negate(y)时,你现在拥有类似于这个lambda'(x,y)=> transform ))'。 –

回答

5

2009年,由于我的问题吕克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<...>::type包装的。这足以限制占位符的范围。