I'd like a constexpr
function that will return me a unique id for every C++ type, something like this:
using typeid_t = uintptr_t;
template <typename T>
constexpr typeid_t type_id() noexcept
{
return typeid_t(type_id<T>);
}
int main()
{
::std::cout << ::std::integral_constant<typeid_t, type_id<float>()>{} << ::std::endl;
return 0;
}
But I get an error:
t.cpp: In function 'int main()':
t.cpp:23:69: error: conversion from pointer type 'typeid_t (*)() noexcept {aka long unsigned int (*)() noexcept}' to arithmetic type 'typeid_t {aka long unsigned int}' in a constant-expression
::std::cout << ::std::integral_constant<typeid_t, type_id<float>()>{} << ::std::endl;
^
t.cpp:23:69: note: in template argument for type 'long unsigned int'
Is there a workaround or another way?
You could use some tricks as shown in this answer.
There's even a library called ctti that utilizes the same trick, it should work out of the box
static_assert(ctti::type_id<int>() != ctti::type_id<float>(), "compile-time type-id comparison");
constexpr auto hash = ctti::type_id<int>().hash();