Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr and RTTI

I'd like to do something like this:

template <typename T>
constexpr ::std::size_t type_name_hash()
{
  return ::std::hash<::std::string>()(typeid(T).name());
}

Now, I know neither hash nor string are constexpr, but this could be worked around, assume they are constexpr. What I want to ask is, if RTTI was turned on, should a constexpr function computing a hash of typeid(T).name() still produce a compile-time constant? How about when RTTI is turned off?

like image 794
user1095108 Avatar asked Sep 14 '25 11:09

user1095108


1 Answers

typeid(type-id) and typeid(expr) can both be used in constant expressions, except if (as has been mentioned) expr's result is a glvalue of polymorphic class type.

However, since none of type_info's standard members are constexpr (including the hash_code() method), you cannot do anything with that object except take its address. There's not even a guarantee in the standard that the object is initialized. And even taking the address is only barely useful because there is no guarantee that typeid() has the same result when used with the same type. E.g. the following assertion may fail:

static_assert(&typeid(int) == &typeid(int), "Multiple type_infos for int");

This is a contrived example, but it's not unheard of that typeid(T) yields different results for the same T in multiple shared libraries used in a program, and possibly even in different translation units.

like image 183
Arne Vogel Avatar answered Sep 16 '25 02:09

Arne Vogel