views:

73

answers:

2

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?

+3  A: 

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.

Johannes Schaub - litb
A: 

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; 
}
Chubsdad