开发者

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) || type开发者_如何学编程id(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, i.e, 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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜