*
sk*@yahoo.com:
I saw this on the message boards but I don't see any explanation on how/why
this works. Doesn't typeid operator only take 1 argument?
template<class T> bool is_polymorphic( const T&r )
{
bool result = false;
typeid(result = true, r);
return result;
}
First, syntax: typeid is an operator, not a function. So the
parenthesis isn't the parenthesis of a function call's argument list.
It's simply a parenthesis, around a comma expression, which is the
single argument to typeid.
The comma operator, when executed, evaluates each argument in sequence
and the result of the expression is the result of the last argument.
Now, semantics. When the expression that is the single argument to
typeid has non-polymorphic static type it isn't evaluated. So in that
case the 'result = true' part isn't executed. But when the expression
is of polymorphic type it is evaluated.
For default-constructible classes an in-practice way of doing this
determination at compile time is
template<class T>
class IsPolymorphic
{
private:
class Derived: T { virtual ~Derived() {} };
public:
enum{ yes = (sizeof(Derived)==sizeof(T)), no = !yes };
};
but this is not guaranteed to work on all compilers, it's only
in-practice, since it relies on (1) having a vtable pointer added when
there are virtual functions, and (2) no size overhead for deriving a
class with no data members, neither of which is guaranteed.
I've never needed either construction, but perhaps determining whether a
class is polymorphic or not, can be useful for something...
Do you recall what it was used for?
Hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?