Reputation: 6566
Why is typeid(someType) not constant like sizeof(someType) ?
This question came up because recently i tried something like:
template <class T>
class Foo
{
static_assert(typeid(T)==typeid(Bar) || typeid(T)==typeid(FooBar));
};
And i am curious why the compiler knows the size of types (sizeof) at compile time, but not the type itself (typeid)
Upvotes: 5
Views: 2908
Reputation: 41331
When you are dealing with types, you'd rather use simple metaprogramming techniques:
#include <type_traits>
template <class T>
void Foo()
{
static_assert((std::is_same<T, int>::value || std::is_same<T, double>::value));
}
int main()
{
Foo<int>();
Foo<float>();
}
where is_same
could be implemented like this:
template <class A, class B>
struct is_same
{
static const bool value = false;
};
template <class A>
struct is_same<A, A>
{
static const bool value = true;
};
typeid
probably isn't compile-time because it has to deal with runtime polymorphic objects, and that is where you'd rather use it (if at all).
Upvotes: 10
Reputation: 45106
C++ can handle constant (compile-time) expressions of some types, but reference types are not among those types. The result of a typeid
expression is a reference to a std::type_info
object.
Apparently for a while in 2008, the C++ standard committee had typeid
expressions such as the ones in your example behaving as constant expressions, just like sizeof
. However, according to this comment, that change was ultimately reverted.
Upvotes: 5
Reputation: 308206
Because typeid
has the flexibility to do lookups at runtime based on a pointer or reference to an object, it can't return a compile-time constant. Even when it looks like it could. sizeof
has no such restrictions, as it always does its calculation at compile time.
Upvotes: 1
Reputation: 16994
It knows the type itself (in its own internal language) at compile time, but not its type id (which has clearly been created for runtime).
Upvotes: 0