smichaud
smichaud

Reputation: 326

Any way to use a method on a template class (when you have a pointer of a base class) when not knowing the used template type

Let's say I have this :

class A 
{
    virtual int Method2(){/*...*/}
};

template<typename T>
class B<T> : public A
{
public :
    virtual int Method1(){/*...*/}
    virtual int Method2(){/*...*/}
};

Is it possible to do something similar to this (this does not work of course...) ?

A* a = ...;

B* b = dynamic_cast<B*>(a);

b->Method1();

Thanks

Upvotes: 1

Views: 118

Answers (5)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

class A 
{
    //...
};

template <class T>  //you missed this line
class B : public A  //note the public keyword
{
public :
    int Method1(){/*...*/}
};

Now you can use

A* a = new B<char>;

B<char>* b = dynamic_cast<B<char>*>(a);

b->Method1();

Note that B is not a class, it's aclass template. So you need to provide template arguments

Upvotes: 0

Puppy
Puppy

Reputation: 146910

What people normally do is have an intermediary class.

class A { virtual ~A() {} };
class B : public A { virtual void method(); }
template<typename T> class C : public B {
    void method() { ... }
};

A* a = new C<int>();
if(B* b = dynamic_cast<B>(a)) {
    b->method();
}

This is known as type erasure. However, in this system, A doesn't really serve much purpose.

Upvotes: 2

Diego Sevilla
Diego Sevilla

Reputation: 29021

B has to have a complete type, that is, B<Something>. Then you can do it as with a normal class, but you cannot do it with the class alone without the type parameter.

Upvotes: 0

John Dibling
John Dibling

Reputation: 101456

No, because B is not a complete type. You can't get a pointer to a B because there's no such thing as a B.

It looks like you're trying to use templates to accomplish run-time polymorphism. Is that right?

Upvotes: 0

Steve Jessop
Steve Jessop

Reputation: 279255

Assuming that you meant:

template<typename T>
class B { and the rest of it }

Then B isn't a class, so there's no such thing as a B*. Unless your code is inside the class template B, that is, in which case B refers to what outsiders call B<T> for some type T.

The contents of the ... is quite important too. This is fine:

A *a = new B<int>();
B<int> *b = static_cast<B<int>*>(a);
b->Method1();

Finally, you can only dynamic_cast if the classes have virtual functions, which in your example they don't.

Upvotes: 1

Related Questions