Am I right to think that this function should only be evaluated at compile time, or is there a run-time cost to it?
template <typename T>
size_t constexpr CompID() {
return typeid(T).hash_code();
}
struct Foo {};
int main(int argc, const char * argv[]) {
size_t foo = CompID<Foo>();
return 0;
}
constexpr function allows the function to be evaluated at compile time, but does not require that, so your answer is “maybe”. It depends on the compiler’s optimization settings.
If you wish to have no runtime cost, you could force compile-time evaluation by assigning it to a constexpr variable, e.g.
Also note that
type_info.hash_code()cannot be evaluated in compile-time (it is not a constexpr function, §18.7.1[type.info]/7). So your code is actually wrong.