简体   繁体   中英

Why is typeid not compile-time constant like sizeof

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)

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, ie, typeid is performed at runtime and BOOST_STATIC_ASSERT is performed at compile time.

More information here .

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.

它在编译时知道类型本身(用它自己的内部语言),但不知道它的类型id(显然是为运行时创建的)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM