Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where in C++14 Standard does it say that a non-constexpr function cannot be used in a definition of a constexpr function?

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;
}

Looking at §7.1.5/3 in C++14 we have:

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) — 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.

like image 433
Ayrosa Avatar asked Dec 14 '15 17:12

Ayrosa


People also ask

Can constexpr functions call non constexpr functions?

A call to a constexpr function produces the same result as a call to an equivalent non- constexpr function , except that a call to a constexpr function can appear in a constant expression. The main function cannot be declared with the constexpr specifier.

Can constexpr call non constexpr?

constexpr function can call only other constexpr function not simple function.

Where is constexpr defined?

The keyword constexpr was introduced in C++11 and improved in C++14. It means constant expression. Like const , it can be applied to variables: A compiler error is raised when any code attempts to modify the value. Unlike const , constexpr can also be applied to functions and class constructors.

Do constexpr functions have to be defined in header?

Constexpr functions are implicitly inline, which means they are suitable to be defined in header files. Like any function in a header, the compiler is more likely to inline it than other functions.


1 Answers

Two paragraphs later, in [dcl.constexpr]/5:

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.

No argument exists such that foo() could be a core constant expression because of incr(), therefore the program is ill-formed (NDR).

like image 137
Barry Avatar answered Sep 28 '22 02:09

Barry