Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++11 constexpr和RTTI_C++11_Constexpr - Fatal编程技术网

C++11 constexpr和RTTI

C++11 constexpr和RTTI,c++11,constexpr,C++11,Constexpr,我想这样做: template <typename T> constexpr ::std::size_t type_name_hash() { return ::std::hash<::std::string>()(typeid(T).name()); } 模板 constexpr::std::size\u t type\u name\u hash() { return::std::hash()(typeid(T).name()); } 现在,我知道hash和st

我想这样做:

template <typename T>
constexpr ::std::size_t type_name_hash()
{
  return ::std::hash<::std::string>()(typeid(T).name());
}
模板
constexpr::std::size\u t type\u name\u hash()
{
return::std::hash()(typeid(T).name());
}

现在,我知道
hash
string
都不是
constepr
,但这是可以解决的,假设它们是
constepr
。我想问的是,如果启用了
RTTI
,那么计算
typeid(T.name()
散列的
constepr
函数是否仍会生成编译时常量?当
RTTI
关闭时如何?

您认为运行时类型标识的哪一部分在编译时起作用?常量表达式的规则不允许:

-一种
typeid
表达式(5.2.8),其操作数是多态类类型的glvalue

因此,您的模板只适用于某些类型

关闭RTTI后,您根本无法使用
typeid

C++11已经提供了散列类型的机制:

return ::std::hash<::std::type_index>()(::std::type_index(typeid(T)));
现在的问题是“唯一”的是
type\u index
构造函数不是
constepr
,哈希函数也不是。

typeid(type id)和typeid(expr)都可以在常量表达式中使用,除非(如上所述)expr的结果是多态类类型的glvalue

但是,由于
type\u info
的标准成员都不是
constepr
(包括
hash\u code()
方法),因此您不能对该对象执行任何操作,只能获取其地址。标准中甚至没有保证对象已初始化。即使使用地址也没有什么用处,因为不能保证typeid()与同一类型一起使用时具有相同的结果。例如,以下断言可能失败:

static_assert(&typeid(int) == &typeid(int), "Multiple type_infos for int");

这是一个人为的例子,但并非没有听说过
typeid(T)
在程序中使用的多个共享库中,甚至可能在不同的翻译单元中,对相同的
T
产生不同的结果。

谢谢,我看到了另一个被遗忘的
constepr
说明符的例子,在编译时,我不能使用
RTTI
做任何事情,除了使用指针。只使用
type\u info
的指针怎么样,
typeid
返回并作为“hash”返回。不能保证
type\u info
的地址是一个常量(可以根据需要动态分配)在这种情况下,不允许在带有多态类类型glvalue的
constexpr
函数typeid表达式中获取其地址,但允许(通过扩展)使用typeid的所有其他用途。示例代码只使用type-id。事实上,GCC认为即使“int x;constexpr auto&tx=typeid(x);”也可以。我认为这并不能回答OP的问题
typeid(T)
显然永远不会遇到这里描述的问题,因为
T
不是表达式,而是类型名。因此,所需的操作可能都是
constexpr
(但它们不是)。
static_assert(&typeid(int) == &typeid(int), "Multiple type_infos for int");