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(){/*开发者_如何学Go...*/}
};
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
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.
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.
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?
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.
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
精彩评论