问题
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?
回答1:
What part of Run-Time Type Identification do you think works at compile-time? The rules for constant expressions disallow:
— a
typeid
expression (5.2.8) whose operand is a glvalue of a polymorphic class type;
so your template would only work for some types.
And with RTTI turned off you can't use typeid
at all.
C++11 already provides a mechanism to hash a type:
return ::std::hash<::std::type_index>()(::std::type_index(typeid(T)));
But it's not going to be a constant expression for all types.
You could use the type_index
of a pointer to each type, as a pointer is not a polymorphic class type and will still give a unique type:
return ::std::hash<::std::type_index>()(::std::type_index(typeid(T*)));
Now the problem is "only" that the type_index
constructor is not constexpr
and neither is the hash function.
回答2:
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.
来源:https://stackoverflow.com/questions/23930319/constexpr-and-rtti