Is it possible to ensure a constexpr function is called at most once at compile time?

前端 未结 1 1211
一个人的身影
一个人的身影 2021-01-01 04:52

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 const

相关标签:
1条回答
  • 2021-01-01 05:03

    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:

    • "NON-CONSTANT CONSTANT-EXPRESSIONS IN C++" - (cached by Google)

    • "HOW TO IMPLEMENT A CONSTANT-EXPRESSION COUNTER IN C++" - (cached by Google)

    • "HOW TO IMPLEMENT A COMPILE-TIME META-CONTAINER IN C++" - (cached by Google)

    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.

    0 讨论(0)
提交回复
热议问题