0

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
  • The other solution would be to make MyClass's constructor take a MyTemplate<MyClass>* argument. Commented Aug 13, 2010 at 22:21
  • @UncleBens In my real code, MyTemplate2 has some additional properties/methods which are used in MyClass's constructor. Commented Aug 13, 2010 at 22:24
  • then do the cast inside the constructor of MyClass, if you don't want to do the cast in the MyTemplate constructor (which would be a bit disturbing, because you would introduce knowledge about existence of derived classes into that base). Commented Aug 13, 2010 at 22:36

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.