我正在努力学习C++模板元编程。给出类的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;
}编辑:
我现在已经做了shure,它实际上是编译的。然而,史蒂文的建议也不起作用。对于这种变化,我得到了以下错误:
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的需求?
非常感谢
发布于 2013-06-05 13:15:10
根据错误消息,看起来您需要类似于
mpl::int_< mpl::at<l, mpl::placeholders::_2>::type::x > > 发布于 2013-11-15 14:57:15
我们需要将一个元函数传递给if_,它可以在折叠扩展后进行延迟评估。
为
mpl::int_< mpl::at<l, mpl::placeholders::_2>::type::x >它将立即执行计算,这将生成无法从表达式中找到'x‘的错误。
您可以尝试使用经过修饰的测试函数,而不是is_same。
template <typename T, typename V>
struct has_value
: mpl::bool_<T::x == V::value>
{};
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_<
has_value<
mpl::at<l, mpl::placeholders::_2>
, mpl::int_<1> >
,
mpl::placeholders::_2, mpl::placeholders::_1 >
> index;
};https://stackoverflow.com/questions/16940390
复制相似问题