这是我想做的:
ExampleTemplate* pointer_to_template;
cin >> number;
switch (number) {
case 1:
pointer_to_template = new ExampleTemplate<int>();
break;
case 2:
pointer_to_template = new ExampleTemplate<double>();
break;
}
pointer_to_template->doStuff();
这不会编译,因为在声明指针时必须指定模板类型。 ( ExampleTemplate* pointer_to_template
应该是 ExampleTemplate<int>* pointer_to_template
。)不幸的是,我不知道模板的类型,直到它在 switch block 中声明。对于这种情况,最好的解决方法是什么?
最佳答案
你不能。 ExampleTemplate<int>
和 ExampleTemplate<double>
是两种不同的、不相关的类型。如果您总是需要切换多个选项,请使用 boost::variant
而是。
typedef boost::variant<Example<int>, Example<double>> ExampleVariant;
ExampleVariant v;
switch (number) {
case 1: v = Example<int>(); break;
case 2: v = Example<double>(); break;
}
// here you need a visitor, see Boost.Variant docs for an example
另一种方法是使用具有虚拟公共(public)接口(interface)的普通基类,但我更喜欢 variant
.
struct BaseExample {
virtual void do_stuff() = 0;
virtual ~BaseExample() {}
};
template <typename T>
struct Example : BaseExample { ... };
// ..
BaseExample *obj;
关于c++ - 如何在不知道类型的情况下声明模板指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8205902/