简体   繁体   中英

Using Boost MPL to Compute Lengths of Vectors

I'm using Boost MPL with C++03 and I'm having issues computing the lengths of mpl::vectors stored within another mpl::vector. For this simple example, the outer vector contains 3 inner vectors, and each inner vector contains just 1 entry which is mpl::int_<0>. The code I'm using is the following:

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

I get an error at the second assert, which is:

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 ::_>>::************)

What am I doing wrong here?

Edit: I discovered the lengths seem to be computed correctly as the following asserts succeed:

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

So the issue is with the assert statement.

jv_ pointed me to the answer, which can be found here (thanks to Andy Little). Basically I was using mpl::equal incorrectly in all of the code above. mpl::equal uses mpl::is_same under the hood (default third template parameter), which checks if types are exactly the same. I need to provide a third template parameter to mpl::equal, mpl::equal_to, such that the values of the integral constants are compared one by one. The final assert statement looks like this:

BOOST_MPL_ASSERT(( mpl::equal<lengths, mpl::vector_c<int, 1, 1, 1>::type, mpl::equal_to<mpl::_1, mpl::_2> >));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM