增强MPL嵌套lambda

Boost MPL nested lambdas

本文关键字:lambda 嵌套 MPL 增强      更新时间:2023-10-16

我一直在努力掌握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;

感谢Luc Touraille对我的问题的评论,Boost邮件列表提供了答案。下面的代码是:

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。这足以绑定占位符的范围。