如何在不知道类型的情况下声明模板指针? [英] How can I declare a template pointer without knowing the type?
问题描述
这是我想要做的:
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
。)不幸的是,我不知道类型该模板,直到它在开关块中声明。
This doesn't compile because the template type must be specified when declaring the pointer. (ExampleTemplate* pointer_to_template
should be ExampleTemplate<int>* pointer_to_template
.) Unfortunately, I don't know the type of the template until it's declared in the switch block. What is the best work around for this situation?
推荐答案
你不能。 ExampleTemplate< int>
和 ExampleTemplate< double>
是两种不同的不相关类型。如果您总是切换多个选项,请改用 boost :: variant
。
You can't. ExampleTemplate<int>
and ExampleTemplate<double>
are two different, unrelated types. If you always have a switch over several options, use boost::variant
instead.
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
$ b b
另一种方法是使用具有虚拟公共接口的普通基类,但我更喜欢 variant
。
struct BaseExample {
virtual void do_stuff() = 0;
virtual ~BaseExample() {}
};
template <typename T>
struct Example : BaseExample { ... };
// ..
BaseExample *obj;
这篇关于如何在不知道类型的情况下声明模板指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!