c++ - 如何在不知道类型的情况下声明模板指针?

标签 c++ templates generics pointers

这是我想做的:

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/

相关文章:

javascript - 删除 html 模板实例

java - 重载方法 : both methods have same erasure

c++ - 模板类中的静态常量成员初始化

c++ - 用于进程间共享内存的非 Boost STL 分配器?

templates - Kendo 模板中的 Switch 语句

c++ - 将控制台应用程序从 VC 6 迁移到 VS 2010

java - 转换为泛型类型时的类型安全警告

.net - 如何在 .NET 中使用 Reflection 区分封闭类型参数和嵌套类型参数?

c++ - 从limemicro编译lms6suite时出现枚举错误

c++ - 生成没有重复的位组合(不是排列)