Martin Perry
Martin Perry

Reputation: 9527

C++11 constexpr and typeid(type)

Is there a way, how to get typeid into variable in compile time using constexpr?

This is not working, since std::type_index has no constexpr ctor

constexpr std::type_index i = typeid(double);

Upvotes: 7

Views: 2811

Answers (2)

Fedor
Fedor

Reputation: 21307

Technically it was possible to take a constexpr reference to a typeid result:

constexpr auto &i = typeid(double);

But

  1. The comparison &i == &typeid(double) is not guaranteed to return true.
  2. It was not supported in constant expressions till GCC 12, bug.

Only in C++23 we get constexpr comparison of type_infos:

constexpr bool type_info::operator==( const type_info& rhs ) const noexcept;

https://en.cppreference.com/w/cpp/types/type_info/operator_cmp

Upvotes: 1

In a way, there is:

constexpr const std::type_info &i = typeid(double);

You have to keep in mind that typeid returns type const std::type_info &, not a std::type_index.

Upvotes: 3

Related Questions