gpt4 book ai didi

c++ - 每种类型的编译时 typeid

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:23:39 28 4
gpt4 key购买 nike

我想要一个 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'

是否有解决方法或其他方法?

最佳答案

您可以使用此 answer 中所示的一些技巧.

甚至还有一个名为 ctti 的图书馆使用相同的技巧,它应该开箱即用

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

constexpr auto hash = ctti::type_id<int>().hash();

关于c++ - 每种类型的编译时 typeid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36117884/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com