[英]Is it possible to ensure a constexpr function is called at most once at compile time?
As the title asks: Is it possible to ensure a constexpr function is called at most once at compile time? 正如标题所示:是否有可能确保在编译时最多调用一次constexpr函数?
This clearly won't be possible if the function is not constepxr; 如果功能不是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.
每当我按空格键时,我都可以编写一个被调用的函数,因此编译器永远无法在编译时解决这个问题。
Short answer: no, because constexpr
functions cannot read/set external state. 简答:不,因为
constexpr
功能无法读取/设置外部状态。 (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 friend
ship and ADL: FilipRoséen有一系列博客文章,通过滥用
friend
船和ADL来介绍有状态constexpr
功能的实现:
"NON-CONSTANT CONSTANT-EXPRESSIONS IN C++" - (cached by Google) “C ++中的非常量常量表达式” - (由Google缓存)
"HOW TO IMPLEMENT A CONSTANT-EXPRESSION COUNTER IN C++" - (cached by Google) “如何在C ++中实现常量表达式计数器” - (由Google缓存)
"HOW TO IMPLEMENT A COMPILE-TIME META-CONTAINER IN C++" - (cached by Google) “如何在C ++中实现兼容的META-CONTAINER” - (由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 .
它被认为是由CWG的功能滥用, 这是试图与问题#2118是病态的 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.