我有各种不同的数据类型。想将它们存储在向量/树(例如数据的目录结构)中,但在某些时候我需要获得真实类型并对实际类型进行操作。例如通过对每个类的成员执行boost :: fusion :: for_each来打印它们。我查看了以下解决方案的选择:
我尝试了以下方法。有什么方法可以从最后一个循环的某个地方传递模板值吗?不知道如何存储。这是一种鸡蛋问题。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct NullType {};
struct A {};
struct B {};
template <int i=0>
struct Int2Class
{
typedef NullType Type;
};
template <> struct Int2Class<1>
{
typedef A Type;
};
template <> struct Int2Class<2>
{
typedef B Type;
};
struct Base
{
virtual ~Base() {}
};
template <typename T>
struct Data : public Base
{
Data() {}
Data( const T& t ) : t_( t ) {}
T t_;
};
template <typename T>
void ft( const T& t )
{
// do something specific to T
}
int main()
{
A a;
B b;
Base* d1 = new Data<A>( a );
Base* d2 = new Data<B>( b );
std::vector<Base*> v;
v.push_back( d1 );
v.push_back( d2 );
Data<A>* a1 = static_cast<Data<A>*>( d1 );
if( a1 ) cout << "yeah\n";
typedef Data<Int2Class<1>::Type>* Type;
Data<A> *a2 = static_cast<Type>( d1 );
if( a2 ) cout << "yeah2\n";
for( std::vector<Base*>::iterator i = v.begin(); i != v.end();
++i )
{
// for illustration purpose, items in vector is in the order
// of the class Id #, or save that as part of a pair in the
// vector
typedef Data<Int2Class<???>::Type>* Type;
ft( static_cast<Type>( *i ) );
}
}