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

不想你离开。 提交于 2020-01-03 08:42:08

问题


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?
}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/18781832/does-typeidt-get-evaluated-at-run-time-or-compile-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!