为每种类型编译时间typeid

use*_*108 5 c++ c++14

我想要一个constexpr可以为每个C ++类型返回唯一ID 的函数,如下所示:

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;
}
Run Code Online (Sandbox Code Playgroud)

但是我得到一个错误:

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' 
Run Code Online (Sandbox Code Playgroud)

有解决方法或其他方法吗?

Jam*_*ree 7

您可以使用一些技巧,如本答案所示。

甚至还有一个叫做ctti的库,它使用了同样的技巧,它应该是开箱即用的

static_assert(ctti::type_id<int>() != ctti::type_id<float>(), "compile-time type-id comparison");

constexpr auto hash = ctti::type_id<int>().hash();
Run Code Online (Sandbox Code Playgroud)