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)
typeid operator syntaxThe typeid operator requires RunTime Type Identification (RTTI) to be generated, which must be explicitly specified at compile time through a compiler option. The typeid operator returns an lvalue of type const std::type_info that represents the type of expression expr.
The sizeof operator applied to a variable length array type is evaluated at run time, and therefore is not a constant expression.
The typeid operator allows the type of an object to be determined at run time. The result of typeid is a const type_info& . The value is a reference to a type_info object that represents either the type-id or the type of the expression, depending on which form of typeid is used.
The typeid operator is used to determine the class of an object at runtime. It returns a reference to a std::type_info object, which exists until the end of the program, that describes the "object". If the "object" is a dereferenced null pointer, then the operation will throw a std::bad_typeid exception.
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).
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.
Because typeid requires RTTI, i.e, typeid is performed at runtime and BOOST_STATIC_ASSERT is performed at compile time.
More information here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With