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?