【问题标题】:Using Boost MPL to Compute Lengths of Vectors使用 Boost MPL 计算向量的长度
【发布时间】:2016-03-23 16:47:21
【问题描述】:

我在 C++03 中使用 Boost MPL,但在计算存储在另一个 mpl::vector 中的 mpl::vectors 长度时遇到问题。对于这个简单的示例,外部向量包含 3 个内部向量,每个内部向量仅包含 1 个条目,即 mpl::int_。我使用的代码如下:

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> ));

我在第二个断言处得到一个错误,即:

错误:没有函数模板“mpl_::assertion_failed”的实例 匹配参数列表

参数类型有:(mpl_::failed ************boost::mpl::equal, boost::mpl::v_item, boost::mpl::v_item, boost::mpl::vector0<:na>, 0>, 0>, 0>, boost::mpl::vector3_c, boost::is_same, 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_ 是的,那是我的问题。谢谢。
  • 第二次编辑将是一个完美的答案(也许删除 jv_ 并将此人记入邮件列表中)。
  • 我的意思是说您应该复制您的第二次编辑并将其作为答案发布,因为它完美地解释了问题和解决方案。
  • @jv_ 完成。再次感谢。

标签: c++ templates boost


【解决方案1】:

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> >));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    相关资源
    最近更新 更多