不需要constexpr函数来返回常量表达式吗? [英] A constexpr function is not required to return a constant expression?

查看:140
本文介绍了不需要constexpr函数来返回常量表达式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++入门(第5版)在第240页上有一条注释,指出:

C++ Primer (5th edition) on page 240 has a note stating:


A constexpr 函数不需要返回常量表达式。

"A constexpr function is not required to return a constant expression".

有人问了这个问题: constexpr函数返回类型可以为非const吗?。该问题的作者误解了该说明。

A question has been asked about this: can constexpr function return type be a non const?. The author of that question misunderstood the note.

但是对它的正确理解是什么(引用的帖子的答案澄清了该帖子作者的困惑,但没有回答我的问题)?

But what is the correct understanding of it (the answers to the cited post clarify the confusion of that post's author, but do not answer my question)?

推荐答案

一个(非模板) constexpr 函数必须至少具有一个执行路径,返回一个常量表达式;形式上,必须存在参数值,以使对函数[...]的调用可以是核心常量表达式的评估子表达式 [dcl.constexpr] / 5)。例如(同上):

A (non-template) constexpr function must have at least one execution path that returns a constant expression; formally, there must exist argument values such that "an invocation of the function [...] could be an evaluated subexpression of a core constant expression" ([dcl.constexpr]/5). For example (ibid.):

constexpr int f(bool b) { return b ? throw 0 : 0; }     // OK
constexpr int f() { return f(true); }     // ill-formed, no diagnostic required

此处 int f(bool )允许为 constexpr ,因为其对参数值 false 的调用将返回一个常量表达式。

Here int f(bool) is allowed to be constexpr because its invocation with argument value false returns a constant expression.

可能有一个 constexpr 函数,如果该函数的特殊化,则该函数永远无法返回常量表达式。一个函数模板,该模板可能至少具有一个能返回常量表达式的特殊化对象。同样,使用上述内容:

It is possible to have a constexpr function that cannot ever return a constant expression if it is a specialization of a function template that could have at least one specialization that does return a constant expression. Again, with the above:

template<bool B> constexpr int g() { return f(B); }    // OK
constexpr int h() { return g<true>(); }    // ill-formed, no diagnostic required

这篇关于不需要constexpr函数来返回常量表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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