Reputation: 5957
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?
Upvotes: 0
Views: 188
Reputation: 25487
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;
}
Upvotes: 0
Reputation: 506847
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.
Upvotes: 3