我想要一个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;
}
但是我得到一个错误:
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' 
有解决方法或其他方法吗?
您可以使用一些技巧,如本答案所示。
甚至还有一个叫做ctti的库,它使用了同样的技巧,它应该是开箱即用的
static_assert(ctti::type_id<int>() != ctti::type_id<float>(), "compile-time type-id comparison");
constexpr auto hash = ctti::type_id<int>().hash();
| 归档时间: | 
 | 
| 查看次数: | 4910 次 | 
| 最近记录: |