C ++店相同的类与数组不同的模板 [英] C++ store same classes with different templates in array

查看:176
本文介绍了C ++店相同的类与数组不同的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

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

现在我需要这个类有不同的模板类似的实例数组:

Now I need an array of instances of this class with different templates like:

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

的std ::矢量&lt; A * GT;阵列; 不会工作,因为我显然需要指定一个模板,但我不能这样,因为我存储不同类型此数组中为止。是否有某种泛型类型或其他解决方案?

But std::vector<A*> array; wont work, because I apparently need to specify a Template, but i can't so that because I store different types in this array. Is there some kind of generic type or an other solution?

推荐答案

您需要一个基类:

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>);

这篇关于C ++店相同的类与数组不同的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆