c++ - 使用 Boost MPL 计算 vector 长度

标签 c++ templates boost

我在 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/

相关文章:

c++ - pthread_join 因核心转储段错误而崩溃

c++ - const 的 const 数组,在数组长度定义上使用其元素或给模板参数值

c++ - 处理值和引用语义的模板类

c++ - 有没有更好的方法从静态和非静态函数返回相同的字符串文字?

c++ - 如何通过boost.gil从内存中加载图片?

c++将_bstr_t转换为int并将int转换为_bstr_t

C++ 模板作为模板的参数

c++ - 与 boost 波链接时的链接器 'undefined references'错误

c++ - 删除引用计数大于零的拥有对象的引用计数智能指针?

c++ - 运算符++ 中的 Int 参数