开发者

inheriting from a template class causes errors

I have a template class MyTemplate. It works fine. But as soon as I create another class that derives from it, I get errors.

//main.cpp
template <typename T> class MyTemplate {
    public:
        T* test() {
            return new T(this); //error here.
        }
};

template <typename T> class MyTemplate2 : public MyTemplate<T> { 
};

class MyClass {
    public:
        MyClass(MyTemplate2<MyClass>* source) {
        }
};

int main() {
    MyTemplate2<MyClass>().test();
    return 0;
}

The error I get is: main.cpp|4|error: invalid conversion from 'MyTemplate<MyClass>* const' to 'MyTemplate2<MyClass>*'

As I understand the error, "this" in开发者_如何转开发 MyTemplate is of type MyTemplate. But I want it to be MyTemplate2. I can do an explicit cast, but this requires passing a second argument to the template class, and it seems like there should be a better solution to this. Is there?


What you try is simply to pass a Base* (which is this) to a Derived*, which is the wrong way around. You need to explicitly cast to perform this downward conversion.


How about using the "clone" approach?

template <typename T> class MyTemplate { 
    public: 
        T* test() { 
            return clone(); //error here. 
        } 
        virtual T *clone() = 0;
}; 

template <typename T> class MyTemplate2 : public MyTemplate<T> {  
    public:
        T *clone(){return new T(this);}
}; 

class MyClass { 
    public: 
        MyClass(MyTemplate2<MyClass>* source) { 
        } 
}; 

int main() { 
    MyTemplate2<MyClass>().test(); 
    return 0; 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜