简体   繁体   English

是否有可能确保在编译时最多调用一次constexpr函数?

[英]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功能的实现:

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.

相关问题 是否可以测试是否在编译时评估了 constexpr 函数? - Is it possible to test if a constexpr function is evaluated at compile time? 调用 constexpr 函数的给定重载时触发编译时错误 - Trigger compile time error when given overload of the constexpr function is called 如何确保在运行时永远不会调用 constexpr 函数? - How to ensure constexpr function never called at runtime? 使用非constexpr函数设置constexpr变量(但可以在编译时计算) - Set constexpr variable with non-constexpr function (but is possible to compute in compile time) 是否可以在编译时检测是否调用了 function - Is it possible to detect if a function is called at compile time 传递constexpr函数以在编译时使用 - Passing a constexpr function to use at compile time constexpr函数在编译时不计算值 - constexpr function not calculate value in compile time 是什么阻止了这个 constexpr function 的编译时评估? - What is preventing compile time evaluation of this constexpr function? 用于编译时强制constexpr函数求值的单表达式帮助器可能吗? - single expression helper for compile-time enforced constexpr function evaluation possible? 如果忽略结果,则不会在编译时调用 Consexpr 函数 - Constexpr functions not called at compile-time if result is ignored
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM