代码之家  ›  专栏  ›  技术社区  ›  Sebastian Dusza

C++模板与继承

  •  4
  • Sebastian Dusza  · 技术社区  · 14 年前

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

    以后,我能像这样使用这些类吗:

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

    谢谢你的帮助。

    3 回复  |  直到 14 年前
        1
  •  6
  •   John Dibling    14 年前

    你可以,但它不会像你想象的那样有用。您可以这样定义结构:

    #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();
    }
    

    Base<int> 完全不同于 Base<string> Base* 指的是任何一个。

    此代码不会编译:

    vector<Base*> my_objs;
    
        2
  •  7
  •   sharptooth    14 年前

        3
  •  1
  •   Chubsdad    14 年前

    可以将任何类型与类模板一起使用,前提是该类型与类定义兼容

    例如

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

    这样的结构可以为T=int,T=double实例化,但不能为T=void实例化。