constexpr是“提示”吗? (例如内联)或“绑定请求”编译器? [英] Is constexpr a "hint" (like inline) or "a binding request" to the compiler?

查看:77
本文介绍了constexpr是“提示”吗? (例如内联)或“绑定请求”编译器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

constexpr 是编译器的指示符,还是强制行为?

Is constexpr an indicator for the compiler or does it mandate a behaviour ?

下面的示例如下:

template<typename T> 
std::size_t constexpr getID() { return typeid(T).hash_code(); }

hash_code 是运行时常量,但是即使要求使用 constexpr 编译。 c>。只有在期望返回编译时间常数的情况下使用返回值之后,我们才会注意到此不能用作constexpr函数

hash_code is a runtime constant, yet this snippet would compile even though a compile time evaluation is requested with constexpr. Only after the return value is used where a compile time constant is expected, would we get noticed that this is not usable as a constexpr function.

constexpr 也是一个提示(很像 inline 关键字)还是对编译器的绑定请求?

So is constexpr a "hint" (much like the inline keyword) or "a binding request" to the compiler ?

推荐答案

来自 C ++ 11 Wiki页面


如果使用
不是常量表达式的参数调用constexpr函数或构造函数,则该调用的行为就好像该函数是
不是constexpr一样,并且结果值不是常数表达式。
同样,如果constexpr
函数的return语句中的表达式未针对特定的
调用求值为常量表达式,则结果不是常量表达式。

If a constexpr function or constructor is called with arguments which aren't constant expressions, the call behaves as if the function were not constexpr, and the resulting value is not a constant expression. Likewise, if the expression in the return statement of a constexpr function does not evaluate to a constant expression for a particular invocation, the result is not a constant expression.

constexpr 说明符因此表示在编译时评估某些内容的可能性时间,并且在使用时受到一些限制

The constexpr specifier thus expresses the possibility to evaluate something at compile time and is subject to some restrictions when used.

对于您的特定代码段,在我看来C ++ 11约束为:

For your particular snippet it seems to me that the C++11 constraint:


仅包含文字值,
constexpr变量和函数的一个返回语句

未实现,因为hash_code定义为:

is not fulfilled, as hash_code is defined to be:

size_t hash_code() const;

在这种情况下,标准草案n3242 说:


对于constexpr函数,如果不存在
这样的函数参数值,以至于函数调用替换将生成常量
表达式(5.19),则程序格式错误;无需诊断。

For a constexpr function, if no function argument values exist such that the function invocation substitution would produce a constant expression (5.19), the program is ill-formed; no diagnostic required.

我相信您的示例适合此处。

I believe your example fits here.

这篇关于constexpr是“提示”吗? (例如内联)或“绑定请求”编译器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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