用自己的函数转换mpl矢量

tgm*_*ath 4 c++ metaprogramming boost-mpl

我希望将每个元素乘以mpl::vector一个int.首先,一元函数乘以一个int_int.

template <int i>
struct multiply_scalar
{
    template<typename T> struct apply
    {
        typedef int_<(T::value * i)> type;
    };
};
Run Code Online (Sandbox Code Playgroud)

这是我想要的电话.

typedef vector<int_<3>, int_<4> > my_vec;
typedef typename transform< my_vec,  multiply_scalar<2> >::type my_vec_2;

typedef vector<int_<6>, int_<8> > my_vec_3;

BOOST_MPL_ASSERT(( boost::is_same< my_vec_2, my_vec_3 > )); //Fails
//type of my_vec2 is: boost::mpl::v_item<mpl_::int_<8>, boost::mpl::v_item<mpl_::int_<6>, boost::mpl::vector0<mpl_::na>, 0>, 0>
Run Code Online (Sandbox Code Playgroud)

为什么结果向量不是简单的vector<int_<6>, int_<8>>?我拿错了吗?可能是元函数或变换没有以正确的方式应用.

Lou*_*nne 6

主要是因为C++ 03中的一些实现问题,MPL的编写者不得不使用非显而易见的技术来表示序列,其中一个是类型的使用

boost::mpl::vector0<>
boost::mpl::vector1<T>
boost::mpl::vector2<T, U>
... etc
Run Code Online (Sandbox Code Playgroud)

而不是简单的写作

boost::mpl::vector<>
boost::mpl::vector<T>
boost::mpl::vector<T, U>
Run Code Online (Sandbox Code Playgroud)

就像在C++ 11及更高版本中使用可变参数模板一样.另一种技术是在向量中插入东西时创建某种反向链表,这是您在示例中看到的内容:

boost::mpl::v_item<mpl_::int_<8>, // 2nd element
    boost::mpl::v_item<mpl_::int_<6>, // 1st element
        boost::mpl::vector0<mpl_::na>, 0>, 0> // empty list
Run Code Online (Sandbox Code Playgroud)

正因为如此,该文件 对于boost::mpl::transform没有指定究竟是什么类型boost::mpl::transform<s,op,in>::type.实际上,它只保证它是一个等价的类型

typedef lambda<op>::type f;
typedef lambda<in::operation>::type in_op;

typedef fold<
      s
    , in::state
    , bind< in_op, _1, bind<f, _2> >
    >::type r; // <-- the return type is equivalent to this r
Run Code Online (Sandbox Code Playgroud)

这可能对你没有帮助,除非你已经足够了解你没有问过关于它的问题;-),所以基本上它意味着它返回一个类似a的新类型boost::mpl::vector,除了它的实际类型就像我上面展示的一样.特别是,这种类型保证是前向序列概念的模型.

当你使用boost::is_same<T, U>,你实际上是在问是否TU精确的相同类型.你现在应该清楚地看到为什么这不是你真正想要的.相反,您希望对这两个序列进行某种深度比较,这两个序列都代表向量.要检查两个正向序列是否相等,您必须使用该boost::mpl::equal 算法.以下将有效:

#include <boost/mpl/assert.hpp>
#include <boost/mpl/equal.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/vector.hpp>


using namespace boost::mpl;
template <int i>
struct multiply_scalar
{
    template<typename T> struct apply
    {
        typedef int_<(T::value * i)> type;
    };
};

typedef vector<int_<3>, int_<4> > my_vec;
typedef transform< my_vec,  multiply_scalar<2> >::type my_vec_2;

typedef vector<int_<6>, int_<8> > my_vec_3;

BOOST_MPL_ASSERT(( boost::mpl::equal< my_vec_2, my_vec_3 > ));
Run Code Online (Sandbox Code Playgroud)