Boost logo

Boost :

From: Valentin Bonnard (Bonnard.V_at_[hidden])
Date: 2000-07-30 14:09:04

Daryle Walker wrote:

> Is there a template class that helps indicate whether or not a type is
> polymorphic (i.e. dynamic_cast can work with it)?


> If not, how can we make one?

This is sometimes discussed in comp.lang.c++.moderated.
There are no good, general solutions.

You want to determine if type B is polymorphic.

We can check if type D, derived from B, is polymorphic
(it is iff B is polymorphic also):

struct D : B {} d;
bool is_poly = typeid ((B&) d) == typeid (D);

Precondition: B is default constructible.

Or,if we make some assumptions about the layout
of classes:

struct D : B { virtual ~D (); };
const bool is_poly = sizeof (D) == sizeof (B);

Here we assume that a non polymorphic class has no vtable
pointer, so D would have to be larger than B. It will or
won't work if B has a virtual base classes but no virtual
functions, depending on the way vitual bases are accessed
(by the vtable or by an index in the object itself).

The other question is: when do you need to know if a class
is polymorphic or not ?

Unless some Boost component needs to know that, this
discution is probably more appropriate in

Valentin Bonnard

Boost list run by bdawes at, gregod at, cpdaniel at, john at