【发布时间】:2013-10-28 08:38:26
【问题描述】:
我想做精确的this 来获取类型/类的列表。但我不能使用 C++11。有什么建议我可以将类型附加到模板列表吗?
编辑:一些我想做的代码:
#include <iostream>
#include <typeinfo>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/for_each.hpp>
using namespace std;
class A {};
class B {};
class C {};
typedef boost::mpl::vector<> type1;
// supposed I'd like to have this as a #define macro so someone can call
// REGISTER_CLASS(A) and push the type into a list
typedef boost::mpl::push_back<type1, A> type2;
typedef boost::mpl::push_back<type2, B> type3;
typedef boost::mpl::push_back<type3, C> type4;
template <typename T> struct wrap {};
struct Print
{
template <typename T> void operator()( wrap<T> t ) const
{
cout << typeid( T ).name() << endl;
}
};
int main()
{
// this doesn't compile because type4 is a sequence of sequence
// supposed, I need to "flatten" this list so it's eqv to vector<A,B,C>
boost::mpl::for_each<type4, wrap<boost::mpl::placeholders::_1> >( Print() );
// second problem is that I'd like to have typedef of 1 typelist only, not
// type1, type2, ... typeN, since I don't know the exact number of classes
return 0;
}
【问题讨论】:
-
你看Boost.MPL了吗?
-
是的,虽然我对元编程很陌生。任何进一步的指针表示赞赏。如何将类型 T 附加到例如向量,不用重新typedef类型列表?
-
“将类型 T 附加到例如向量”是什么意思?你能举一个例子来说明你想要完成的事情吗?我现在看不到矢量在哪里播放
-
@surfcode 模板元编程是 100% 功能性的 - 这意味着一切都是不可变的。不可变的
push()实际上是returnCopyWithNewElementPushed()。这意味着 only 的追加方式是 typedefing。 -
@nijansen,Angew:感谢您的回复。编辑帖子以更好地描述问题。
标签: c++ metaprogramming template-meta-programming