我想学习C++模板元编程。给定一个boost :: mpl ::类的向量我想计算该类的索引,其中一个静态成员变量具有特定的值。boost-mpl,折叠和占位符,从向量中选择类
我找到了一个似乎可行的解决方案。但是,为了正确编译,我需要一些看似不必要的奇怪'包装类'。这里是我的代码:
#include <iostream>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/range_c.hpp>
using namespace boost;
template<typename T>
struct get_ind {
typedef mpl::int_<T::type::value> type;
};
template <typename T>
struct get_x {
typedef mpl::int_<T::x> type;
};
template<typename l>
struct clist {
typedef mpl::range_c<int, 0, mpl::size<l>::type::value > indices;
typedef mpl::fold<
indices, mpl::size<l>,
mpl::if_<
is_same<
// HERE:
get_x<mpl::at<l, get_ind<mpl::placeholders::_2> > >
//
// mpl::int_< mpl::at<l, mpl::placeholders::_2>::type::x >
// mpl::int_<mpl::at<l, mpl::placeholders::_2> >::x >
, mpl::int_<1> >
,
mpl::placeholders::_2, mpl::placeholders::_1 >
> index;
};
struct A {
static const int x = 1;
};
struct B {
static const int x = 0;
};
int main(int argc, char*argv[]) {
typedef boost::mpl::vector<A, B> classes;
typedef clist<classes> classlist;
std::cout << "result " << classlist::index::type::value<<std::endl;
return 0;
}
编辑:
我已经使舒尔它实际上编译。但是,史蒂文的建议也行不通。对于这种变化,我得到这些错误:
test.cpp: In instantiation of ‘clist<boost::mpl::vector<A, B, mpl_::na, mpl_::na,
mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_
::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na> >’:
test.cpp:56: instantiated from here
test.cpp:38: error: ‘x’ is not a member of ‘mpl_::void_’
test.cpp: In function ‘int main(int, char**)’:
test.cpp:56: error: ‘classlist::index’ is not a class or namespace
任何人都可以请向我解释什么是错误的,我第一个解决方案(注释),我怎样才能避免需要上课get_x和get_ind?
千恩万谢
在我的环境中它不能编译。请添加'#include'和'使用命名空间提升;'在另一个包含之后。在添加这个并尝试你的其他变体之后,除了很多其他的错误外,结果是一个语法错误。在工作解决方案中有3'<' and 3 '>',而不工作的是2'<' and 3 '>'。你必须解决这个问题,我认为你应该在格式化和记录方面做更多的工作。 –