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

感情迁移 提交于 2019-11-29 22:40:13

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/41939704/is-it-possible-to-ensure-a-constexpr-function-is-called-at-most-once-at-compile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!