4

As the title asks: Is it possible to ensure a constexpr function is called at most once at compile time?

This clearly won't be possible if the function is not constepxr; I could write a function that gets called whenever I press the space bar, so the compiler could never figure that out at compile time.

jaggedSpire
  • 4,423
  • 2
  • 26
  • 52
rwols
  • 2,968
  • 2
  • 19
  • 26
  • 3
    constexpr expressions/functions don't have side effects, so it does not matter how often they are called (except for runtime/performance). So why do you want to make sure a constexpr is evaluated only once? – Werner Henze Jan 30 '17 at 15:39
  • @WernerHenze "So why do you want to make sure a constexpr is evaluated only once?" just curiosity and to find the boundaries of a language :-) – rwols Jan 30 '17 at 15:45
  • @rwols: The problem is that "called only once" is a meaningless concept for a `constexpr` function at compile time. It may literally be called one and a half time (!) - implementations can cache the evaluation of constexpr expressions, and this can include partial caching . – MSalters Jan 30 '17 at 16:46
  • 1
    if you use precompiled headers and run `constexpr` function as: `constexpr auto result = function(args...);` in a header, then, maybe, compiler will only compute it once – Andrei R. Jan 31 '17 at 08:20

1 Answers1

13

Short answer: no, because constexpr functions cannot read/set external state. (They can have internal state, but they still need to be "pure").


Real answer: probably yes, but it's a bad idea. There is a series of blog posts by Filip Roséen which covers the implementation of stateful constexpr functions by abusing friendship and ADL:

The technique is very arcane and complicated. It is considered an abuse of features by CWG, which is trying to make it ill-formed with issue #2118.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416