Boost logo

Boost :

From: James Slaughter (James_at_[hidden])
Date: 2000-07-30 14:58:14

I remember a posting to comp.lang.c++.moderated, by Luis Coelho on 23
December 1998 03:41 (GMT):

<---- Begin Quote ---->
Hi, I was having breakfast the other day, when I came up with a
simple function to check whether a type is polymorphic.
First, here's the code:

template <typename T>
bool is_polymorphic(const T& t)
 bool result = false;
 typeid( (result = true) ? t : t);
 return result;

Now why it works:
typeid() actually does two very different things in two very
similar contexts. If it is fed a simple non-polymorphic type it
just gives you the static type and does not evalute its type
(this is also how sizeof works). However if it gets a polymorphic
type, then it evaluates its argument and gives you the dynamic
<---- End Quote ---->

Unfortunately, we don't get a compile time constant out of this technique.
To be honest though, I never found a use for it... is there one?

Best Regards,
James Slaughter.

> -----Original Message-----
> From: bonnard_at_[hidden] [mailto:bonnard_at_[hidden]]On Behalf Of
> Valentin Bonnard
> Sent: Sunday, July 30, 2000 8:09 PM
> To: boost_at_[hidden]
> Subject: Re: [boost] is_polymorphic?
> 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)?
> No
> > 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
> comp.lang.c++.moderated.
> --
> Valentin Bonnard

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