为每种类型编译时间typeid [英] compile time typeid for every type
本文介绍了为每种类型编译时间typeid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个 constexpr
函数,该函数将为我返回每种C ++类型的唯一ID,如下所示:
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;
}
但是我得到一个错误:
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.
甚至还有一个名为 ctti ,它应该可以立即使用
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();
这篇关于为每种类型编译时间typeid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文