Search code examples
c++c++11templatesconstexpr

Can C++ compilers cache the result of constexpr functions?


Disclaimer: This question is a bit complicated because it's several questions in one, but they're all related to the same sort of concept/issue.

Premise: constexpr functions may only consist of a single return statement.

They can call other functions and use conditionals, but theoretically they should demonstrate functional purity, and thus the results should be cachable (by the compiler, at compile time) in some sort of map so that the compiler doesn't have to constantly re-evaluate the same function.

Questions:

  1. Is this assumption correct?
  2. If not, is there something I haven't considered that makes it impossible to cache the result of a constexpr function?
  3. Would that mean that constexpr functions have to be calculated every time they're used?
  4. Are constexpr values on templates cachable or do they also have to be recalculated each time?

Solution

  • I don't believe constexpr functions are required to be pure - at least, not for all possible arguments. Consider:

    #include <iostream>
    #include <stdlib.h>
    
    constexpr int f(int n) { return n == 0 ? 42 : rand(); }
    
    template <int n> void g() {}
    
    int main()
    {
        g<f(0)>();  // OK
    //    g<f(1)>();  // error
        std::cout << f(0) << ' ' << f(1) << ' ' << f(2);
    }
    

    Output: 42 1804289383 846930886. Demo