Do constexpr functions have to be defined before they are used?

82 Views Asked by At

see code below, f() is defined below main function is regarded as ill-formed ? could anyone give me an explanation for this ?

constexpr  int f ();
void indirection ();
int main () {
  constexpr int n = f (); // ill-formed, `int f ()` is not yet defined
  indirection ();
}
constexpr int f () {
  return 0;
}
void indirection () {
  constexpr int n = f (); // ok
}
2

There are 2 best solutions below

0
On BEST ANSWER

The C++14 standard provides the following code snippet (shortened by me for convenience):

constexpr void square(int &x); // OK: declaration

struct pixel { 
    int x;
    int y;
    constexpr pixel(int); 
};

constexpr pixel::pixel(int a)
    : x(a), y(x) 
{ square(x); }

constexpr pixel small(2); // error: square not defined, so small(2)
                        // is not constant so constexpr not satisfied

constexpr void square(int &x) { // OK: definition
   x *= x;
}

The solution is to move the definition of square above the the declaration of small.

From the above we can get to the conclusion that it's fine to forward declare constexpr functions, but their definitions have to be available prior to their first use.

0
On

A constexpr something has to be known at compile time, at each point where it's used.

This is essentially the same as you cannot declare a variable of an incomplete type, even if that type is fully defined later in the same source.