This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
Re: templates, derived classes, and dynamic_cast
- To: cmason at cmu dot edu
- Subject: Re: templates, derived classes, and dynamic_cast
- From: "Martin v. Loewis" <martin at loewis dot home dot cs dot tu-berlin dot de>
- Date: Thu, 16 Mar 2000 10:55:09 +0100
- CC: gcc-bugs at gcc dot gnu dot org, cmason+bio at ash dot rem dot cmu dot edu, post+comp dot lang dot c++ at andrew dot cmu dot edu
- References: <38D070F2.E10E8654@cmu.edu>
> I've found something weird involving templates and dynamic_cast, and I
> don't know whether it's an error in my program or a deficiency or bug in
> g++. Dynamic_casting (a base class pointer to (a template class whose
> template parameter is a derived class)) into (a template class pointer
> to a (template class whose template parameter is a base class)) fails.
To see what's really going on, I put the lines
cout<<"put:"<<typeid(any<T>).name()<<endl;
and
cout<<"get:"<<typeid(any<T>).name()<<endl;
into your code, and get the output
put:t3any1ZP4Base
get:t3any1ZP4Base
Base worked.
put:t3any1ZP7Derived
get:t3any1ZP4Base
dynamic_cast() failed.
Derived didn't work.
So in the second case, you are trying to convert an object of the
dynamic type any<Derived*>* to any<Base*>*
> There's nothing in (the 2 Dec 1999 draft version of) the C++ std which
> directly discusses dynamic_casting of templates. So I can't say for
> sure if this code is or is not correct, as far as the standard is
> concerned.
The matter is that you don't dynamic_cast templates. Instead, you
always convert between pointers and references to class
types. Therefore, the rules for dynamic-casting class types equally
apply to instantiated class templates: If the instantiated classes are
related through inheritance, casting works; if they are not, casting
fails.
Since any<Derived*> is neither base nor derived from any<Base*>, and
since the complete object also does not have subobjects of both types,
the dynamic cast fails.
> I didn't dream this up. The code is after an article by Andrew Koenig:
>
> Koenig, Andrew. Designing a C++ container class. JOOP February 1992
> pg 37.
I don't have the article right now, but I doubt Koenig suggested that
your exact code should work in standard C++.
If you question this line of reasoning, please discuss it in one of
the public C++ fora first, eg. comp.lang.c++.moderated, or
comp.std.c++.
Regards,
Martin