在C ++ 14 Standard中,哪里表示不能在constexpr函数的定义中使用非constexpr函数? [英] Where in C++14 Standard does it say that a non-constexpr function cannot be used in a definition of a constexpr function?
问题描述
例如,除非声明constexpr
constexpr
,否则以下代码不会编译:
For example the code below doesn't compile unless incr()
is declared constexpr
:
int incr(int& n) {
return ++n;
}
constexpr int foo() {
int n = 0;
incr(n);
return n;
}
从C ++ 14中的§7.1.5/3看,我们有:
Looking at §7.1.5/3 in C++14 we have:
constexpr函数的定义应满足以下条件 约束:
(3.1)—不得为虚拟(10.3);
(3.2)—其返回类型应为文字类型;
(3.3)—其每个参数类型均应为文字类型;
(3.4)—其功能主体应为=删除,=默认值或不包含
The definition of a constexpr function shall satisfy the following constraints:
(3.1) — it shall not be virtual (10.3);
(3.2) — its return type shall be a literal type;
(3.3) — each of its parameter types shall be a literal type;
(3.4) — its function-body shall be = delete, = default, or a compound-statement that does not contain
(3.4.1)-一个asm定义,
(3.4.2)— goto语句,
(3.4.3)-一个try-block,或
(3.4.4)—变量的定义
非文字类型,或静态或线程存储持续时间,或
不执行初始化.
(3.4.1) — an asm-definition,
(3.4.2) — a goto statement,
(3.4.3) — a try-block, or
(3.4.4) — a definition of a variable of
non-literal type or of static or thread storage duration or for which
no initialization is performed.
推荐答案
稍后在[dcl.constexpr]/5中的两个段落:
Two paragraphs later, in [dcl.constexpr]/5:
对于非模板,非默认
constexpr
函数或非模板,非默认,非继承 constexpr构造函数,如果不存在任何参数值,则导致调用该函数或构造函数 可以是核心常量表达式(5.20)的求值子表达式,或者对于构造函数而言,可以是常量 某个对象的初始值设定项(3.6.2),程序格式错误;无需诊断.
For a non-template, non-defaulted
constexpr
function or a non-template, non-defaulted, non-inheriting constexpr constructor, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression (5.20), or, for a constructor, a constant initializer for some object (3.6.2), the program is ill-formed; no diagnostic required.
由于存在incr()
,因此不存在使foo()
成为核心常量表达式的参数,因此程序的格式不正确(NDR).
No argument exists such that foo()
could be a core constant expression because of incr()
, therefore the program is ill-formed (NDR).
这篇关于在C ++ 14 Standard中,哪里表示不能在constexpr函数的定义中使用非constexpr函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!