vendredi 27 mars 2015

calling static methods of a templated superclass

I have a templated class A<T> that contains a static method foo() that returns an A<T> *. I have a subclass B which simply specializes to A<int>.


To avoid code duplication, I'd like B to take advantage of A's static foo() method. However, the following gets a compilation error: error: cannot initialize return object of type 'B *' with an rvalue of type 'A<int> *') But B * is exactly A<int> *, no?


Is there a way for B to use A's foo() method?



template <typename T>
class A {
public:
static A *foo() {
// imagine complex code here
return new A<T>();
}
};

// B is a typed specialization of A
class B : public A<int> {
public:
static B *foo() {
return A<int>::foo(); // doesn't compile
}
};

int main() {
B *b = B::foo();
(void)b; // suppress unused variable warning
}

Aucun commentaire:

Enregistrer un commentaire