Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does typeid(T) get evaluated at run time or compile time?

I cannot find the answer to this seemingly simple question anywhere.

Does the following C++ function use RTTI? It certainly doesn't have to, but I was wondering if there is a guarantee that typeid will be determined at compile time.

template <typename T>
const char *getName()
{
   return typeid(T).name();   // Resolved at compile time?
}
like image 216
Watusimoto Avatar asked Sep 13 '13 08:09

Watusimoto


2 Answers

Since typeid is applied to a type rather than an object, there is no runtime type information, so that overhead won't be a problem.

On the other hand: as far as I can see, the standard makes no requirements regarding when the value will be determined, so there's no guarantee that there's no runtime overhead.


Edit:
Of course, the fact that there's (possibly) no guarantee doesn't mean that it's not a reasonable assumption.
I can't imagine that anyone would write a compiler that didn't evaluate typeid(T) at compile time.

like image 131
molbdnilo Avatar answered Oct 27 '22 20:10

molbdnilo


As I mentioned in a comment, the "Notes" section regarding typeid() on cpp reference says:

When applied to an expression of polymorphic type, evaluation of a typeid expression may involve runtime overhead (a virtual table lookup), otherwise typeid expression is resolved at compile time.

like image 43
piwi Avatar answered Oct 27 '22 22:10

piwi