【问题标题】:C++ store same classes with different templates in arrayC ++在数组中存储具有不同模板的相同类
【发布时间】:2012-11-12 14:35:15
【问题描述】:

我有以下课程:

template <typename T>
class A
{
public:
    void method(const char *buffer);
    // the template T is used inside this method for a local variable
};

现在我需要一个具有不同模板的此类实例数组,例如:

std::vector<A*> array;
array.push_back(new A<uint32_t>);
array.push_back(new A<int32_t>);

但是std::vector&lt;A*&gt; array; 不起作用,因为我显然需要指定一个模板,但我不能这样做,因为我在这个数组中存储了不同的类型。是否有某种泛型类型或其他解决方案?

【问题讨论】:

  • 你能把一个成员函数作为模板,而不是整个类吗?
  • 你可以让所有的As 都从一个基类继承,尽管这往往很糟糕。
  • 除了Martinho说的,A不是类型,是类模板。所以你不能像std::vector&lt;A&gt;那样把它用作模板参数。
  • 如果您不知道something 的参数需要是什么类型,您想如何调用array[0].method(something);
  • @R.MartinhoFernandes 我的目标是选择数组中的一个类并调用method。此时method()应该已经知道使用哪种类型了。

标签: c++ arrays templates containers


【解决方案1】:

你需要一个基类:

class ABase {
public:
    virtual void method(const char *) = 0;
    virtual ~ABase() { }
};

template <typename T>
class A : public ABase
{
public:
    virtual void method(const char *);
};

然后像这样使用它

std::vector<ABase*> array;
array.push_back(new A<uint32_t>);
array.push_back(new A<int32_t>);

【讨论】:

  • ABase 应该有私有或删除的拷贝构造函数和拷贝赋值。
  • @aschepler:我确实错过了虚拟析构函数,但我不确定是什么表明实例应该是不可复制的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
  • 2021-08-14
  • 2019-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多