【发布时间】:2012-01-25 02:44:45
【问题描述】:
我想用运行时变量中可用的数据类型来实例化一个模板类。例如,考虑这个类:
template <typename T, unsigned int U>
class Allocator
{
public:
T * pointer;
Allocator() { pointer = new T[U]; }
~Allocator() { delete [] pointer; }
};
现在我想这样使用它:
int main()
{
string temp = "int";
unsigned int count = 64;
Allocator<temp, count> a;
return 0;
}
有什么办法吗?
我在使用基指针序列化派生类的上下文中遇到了这个问题。我使用RTTI来识别派生类的真实类型,但是真实类型的信息存储在一个字符串中。我的问题是能够从基指针动态转换为类型(在运行时作为字符串可用)。请帮忙。
【问题讨论】:
-
U 必须是模板参数而不是构造函数中的参数有什么原因吗?
-
以上只是手头实际问题的一个例子。虽然这可以通过在这种特殊情况下使 U 成为构造函数参数来轻松解决,但我以这个为例来解决真正的问题......