简体   繁体   English

C ++模板和继承

[英]C++ templates and inheritance

can I mix inheritance and templates this way ? 我可以这样混合继承和模板吗? :

template <class T> 
class AbstractType { // abstract
//....
}

template <class T> 
class Type1 : public AbstractType<T> {
//....
}

And later on, can I use these classes like this: 稍后,我可以像这样使用这些类:

AbstractType<SomeClass>* var1 = new Type1<SomeClass>();

Thx for help. 谢谢你的帮助。

Yes, you can. 是的你可以。 You can use the template parameter for whatever you want, passing into the base templated class included. 您可以将模板参数用于任何您想要的内容,并传递给包含的基本模板化类。

You can, but it's not going to be as useful as you may think. 你可以,但它不会像你想象的那样有用。 You can define the structures like this: 您可以像这样定义结构:

#include <string>
#include <vector>
using namespace std;

template<typename Val>
class Base
{
public:
    virtual Val DoIt() const = 0;
};

template<typename Val>
class Derived : public Base<Val>
{
public:
    Derived(const Val& val) : val_(val) {};
    Val DoIt() const { return val_; }
protected:
    Val val_;
};

int main()
{
    Derived<string> sd("my string");
    string sd_val = sd.DoIt();

    Derived<float> fd(42.0f);
    float fd_val = fd.DoIt();
}

But when you're defining abstract base types, you're often going to want a collection of them, and to be able to call through a base class pointer to get polymorphic behavior. 但是当你定义抽象基类型时,你经常会想要它们的集合,并且能够通过基类指针调用以获得多态行为。 If you templatize the base class, you're not going to be able to do this because each variation of the template parameters will create a different type. 如果您对基类进行模板化,那么您将无法执行此操作,因为模板参数的每个变体都将创建不同的类型。 Base<int> is completely different than Base<string> , and you can't just get a Base* that points to either one. Base<int>Base<string>完全不同,你不能只获得指向任何一个的Base*

This code will not compile: 此代码将无法编译:

vector<Base*> my_objs;

You can use any type with the class template, provided the type is compatible with the class definition 如果类型与类定义兼容,则可以将任何类型与类模板一起使用

eg 例如

template<class T> struct S{
   T mt;
};

Such a struct can be instantiated for T = int, T = double, but not T = void. 这样的结构可以实例化为T = int,T = double,但不是T = void。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM