使用boost::mpl获取向量的大小

Getting size of vector using boost::mpl

本文关键字:向量 获取 boost mpl 使用      更新时间:2023-10-16

我正在尝试编译这段代码&我对泛型编程很陌生。目的是在boost::mpl中获得向量的大小。尝试我的手在boost::mpl。我不知道为什么这段代码不能编译。

错误:类'vectorsum>中的'type'没有命名类型

#include <boost/mpl/distance.hpp>
#include <boost/static_assert.hpp>
#include <boost/mpl/begin_end.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/mpl/equal.hpp>
#include <boost/mpl/greater_equal.hpp>
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/times.hpp>
#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/push_back.hpp>
using namespace boost::mpl;
template <typename Seq>
struct vectorsum_impl
{
    typedef typename boost::mpl::begin<Seq>::type typestart;
    typedef typename boost::mpl::end<Seq>::type  typeend;
    typedef typename boost::mpl::distance<typestart,typeend>::type half_size;
};
template <typename S>
struct vectorsum: vectorsum_impl<S> {};
typedef boost::mpl::vector_c<int, 1, 2, 3, 4> testVec;
typedef vectorsum<testVec>::type testVec2;
main()
{
}

为了获得升压MPL序列的大小,我建议使用boost::mpl::size:

#include <boost/mpl/size.hpp>
#include <boost/mpl/vector_c.hpp>
#include <iostream>
int main()
{
    typedef boost::mpl::vector_c<int, 1, 2, 3, 4> testVec;
    std::cout << boost::mpl::size<testVec>::value;
    return 0;
}
输出:

4

生活例子