我在 C++03 中使用 Boost MPL,但在计算存储在另一个 mpl::vector 中的 mpl::vectors 的长度时遇到了问题。对于这个简单的示例,外部 vector 包含 3 个内部 vector ,每个内部 vector 仅包含 1 个条目,即 mpl::int_<0>。我使用的代码如下:
struct ComputeLengths
{
template <typename vectorOfVectors> struct apply
{
typedef typename mpl::transform
<
vectorOfVectors,
mpl::size<mpl::_1>
>::type type;
};
};
BOOST_MPL_ASSERT(( boost::mpl::equal<vectorOfVectors, mpl::vector<mpl::vector_c<int, 0>, mpl::vector_c<int, 0>, mpl::vector_c<int, 0> >::type> ));
typedef typename ComputeLengths::template apply<vectorOfVectors>::type lengths;
BOOST_MPL_ASSERT(( boost::mpl::equal<lengths, mpl::vector_c<int, 1, 1, 1>::type> ));
我在第二个断言处遇到错误,即:
error: no instance of function template "mpl_::assertion_failed" matches the argument list
argument types are: (mpl_::failed ************boost::mpl::equal< boost::mpl::v_item< mpl_::long_< 1L>, boost::mpl::v_item< mpl_::long_< 1L>, boost::mpl::v_item< mpl_::long_< 1L>, boost::mpl::vector0< mpl_::na>, 0>, 0>, 0>, boost::mpl::vector3_c< int, 1, 1, 1>, boost::is_same< mpl_::, mpl::_>>::************)
我在这里做错了什么?
编辑:我发现长度似乎计算正确,因为以下断言成功:
BOOST_MPL_ASSERT(( boost::mpl::equal< typename mpl::size<vectorOfVectors>::type, typename mpl::int_<3>::type > ));
BOOST_MPL_ASSERT(( boost::mpl::equal< typename mpl::at<vectorOfVectors, mpl::int_<0> >::type, typename mpl::int_<1>::type > ));
BOOST_MPL_ASSERT(( boost::mpl::equal< typename mpl::at<vectorOfVectors, mpl::int_<1> >::type, typename mpl::int_<1>::type > ));
BOOST_MPL_ASSERT(( boost::mpl::equal< typename mpl::at<vectorOfVectors, mpl::int_<2> >::type, typename mpl::int_<1>::type > ));
所以问题出在 assert 语句上。
最佳答案
jv_ 指出了答案,可以找到here (感谢 Andy Little)。基本上我在上面的所有代码中都错误地使用了 mpl::equal 。 mpl::equal 在底层使用 mpl::is_same(默认的第三个模板参数),它检查类型是否完全相同。我需要为 mpl::equal 提供第三个模板参数,mpl::equal_to,以便将整数常量的值一个一个地进行比较。最终的断言语句如下所示:
BOOST_MPL_ASSERT(( mpl::equal<lengths, mpl::vector_c<int, 1, 1, 1>::type, mpl::equal_to<mpl::_1, mpl::_2> >));
关于c++ - 使用 Boost MPL 计算 vector 长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36184065/