Search code examples
c++constexprconstexpr-function

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


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
}

Solution

  • 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.