5

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;
}
ildjarn
  • 62,044
  • 9
  • 127
  • 211
sharvey
  • 7,635
  • 7
  • 48
  • 66

1 Answers1

6

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.

§7.1.5[dcl.constexpr]/7

A call to a constexpr function produces the same result as a call to an equivalent non-constexpr function in all respects except that a call to a constexpr function can appear in a constant expression.

If you wish to have no runtime cost, you could force compile-time evaluation by assigning it to a constexpr variable, e.g.

constexpr auto foo = CompID<Foo>();

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.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • Thanks you very much for a quick and informative answer. Can you think of any workaround to get the hash of a type at compile time? – sharvey Oct 08 '12 at 17:07
  • @sharvey: Why do you need such a hash? Maybe you could use template specialization in those places instead? – kennytm Oct 08 '12 at 17:08
  • Using the hash as key in a map. – sharvey Oct 08 '12 at 17:10
  • @sharvey: You can neither build nor access a map via hash at compile-time either. Don't start thinking that `constexpr` means "I can do anything at compile-time". It's very limited, *on purpose*. – Nicol Bolas Oct 08 '12 at 17:16
  • 1
    @sharvey A "compile-time map" can be easily constructed using specialization. See the `type2int` struct in http://stackoverflow.com/a/1708628/224671 for example. – kennytm Oct 08 '12 at 17:17
  • @NicolBolas: not sure why it's on purpose. – sharvey Oct 09 '12 at 02:16