constexpr和RTTI [英] constexpr and RTTI

查看:65
本文介绍了constexpr和RTTI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

template <typename T>
constexpr ::std::size_t type_name_hash()
{
  return ::std::hash<::std::string>()(typeid(T).name());
}

现在,我都不知道 hash string 都是 constexpr ,但这可以解决,假设它们是 constexpr 。我想问的是,如果打开 RTTI ,是否应该使用 constexpr 函数计算<$ c的哈希值$ c> typeid(T).name()仍然会产生一个编译时常量吗?如何关闭 RTTI

Now, I know neither hash nor string are constexpr, but this could be worked around, assume they are constexpr. What I want to ask is, if RTTI was turned on, should a constexpr function computing a hash of typeid(T).name() still produce a compile-time constant? How about when RTTI is turned off?

推荐答案

运行时类型标识,您认为在编译时可行吗?常量表达式的规则不允许:

What part of Run-Time Type Identification do you think works at compile-time? The rules for constant expressions disallow:


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

— a typeid expression (5.2.8) whose operand is a glvalue of a polymorphic class type;

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

so your template would only work for some types.

并且在关闭RTTI的情况下,您根本不能使用 typeid

And with RTTI turned off you can't use typeid at all.

C ++ 11已经提供了一种哈希类型的机制:

C++11 already provides a mechanism to hash a type:

return ::std::hash<::std::type_index>()(::std::type_index(typeid(T)));

但这并不是所有类型的常量表达式。

But it's not going to be a constant expression for all types.

您可以使用指向每种类型的指针的 type_index ,因为指针不是多态类类型,并且仍会给出唯一的类型:

You could use the type_index of a pointer to each type, as a pointer is not a polymorphic class type and will still give a unique type:

return ::std::hash<::std::type_index>()(::std::type_index(typeid(T*)));

现在的问题是仅是 type_index 构造函数不是 constexpr ,散列函数也不是。

Now the problem is "only" that the type_index constructor is not constexpr and neither is the hash function.

这篇关于constexpr和RTTI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆