为什么constexpr为不纯的函数工作 [英] Why constexpr works for impure functions

查看:178
本文介绍了为什么constexpr为不纯的函数工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在浏览我的一个老问题在constexpr我偶然发现了一个非常重要的评论。
基本上可以归结为:
(这是合法的C ++ 11 :()

  constexpr double f(bool b)
{
return b?42:42 /(rand()+ 1); //如何使用rand;
}

我的问题是标准允许的原因是什么。因为我是一个大风扇的参照透明度,我希望他们有一个很好的理由:),我想知道它。



BTW有相关的Q,但大多数A甚至不提纯事,或者当他们没有指定为什么std允许这个。
constexpr与纯函数之间的关系

解决方案

在标准中,相关要求隐藏在 constexpr 函数的主要需求列表。它在§7.1.5/ 5中:


对于constexpr函数,如果没有函数参数值存在,函数调用替换将产生一个常数表达式(5.19),程序是不成形的;无需诊断。


§5.19定义了常量表达式的要求,因此不能调用 rand ()



放宽的限制允许你有条件的纯函数。您的示例 f(true)是有效的模板参数,但 f(false)不是。

当然,缺点是编译器不会验证 constexpr 函数是否可以用于其预期目的。你需要写测试用例。



Ah,litb的回答也是正确的。 (但这个词的用法更简单。)


while browsing one of my old questions on constexpr I stumbled onto a very(IMHO) important comment. Basically it boils down to : (this is legal C++11 :( )

 constexpr double f(bool b)
 {
 return b? 42:42/(rand()+1); // how pure is rand ;)
 }

My question is what is the reason this is allowed by the standard. Since Im a big fan of referential transparency I hope they have a good reason :) and I would like to know it.

BTW there is related Q but most of the A even dont mention pure thing, or when they do they dont specify the reasoning why std allows this. Relation betwean constexpr and pure functions

解决方案

In the standard, the relevant requirement is buried below the main list of requirements for constexpr functions. It's in §7.1.5/5:

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.

§5.19 defines the requirements for constant expressions, such that you can't call rand().

The relaxed restriction allows you to have functions that are conditionally pure. Your example f(true) is a valid template argument, but f(false) is not.

The downside, of course, is that the compiler won't verify that a constexpr function can actually be used for its intended purpose. You need to write test cases.

Ah, litb's answer is also correct. (But this one is worded more simply.)

这篇关于为什么constexpr为不纯的函数工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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