我一直试图掌握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));
Run Code Online (Sandbox Code Playgroud)
一切都很好.但是,以下尝试无法编译:
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));
Run Code Online (Sandbox Code Playgroud)
我认为这与占位符的范围有关negate_a_list,但我不知道如何解决它.有任何想法吗?我还怀疑我对MPL语法和语义的一些假设是有缺陷的.我会很感激任何关于缓和MPL的提示.
PS以下是上述代码的序言:
#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;
Run Code Online (Sandbox Code Playgroud)
感谢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));
Run Code Online (Sandbox Code Playgroud)
请注意在lambda<...>::typelambda表达式周围添加包装.这足以限制占位符的范围.