在 C++20 中,我们现在拥有constinit. constexpr和consteval。
我现在可以保证静态变量是由 aconstexpr或consteval函数的结果初始化的constinit。好的
我还可以保证使用consteval在编译时执行的函数的结果来初始化堆栈变量。
但是如何强制运行一个constexpr函数来计算编译时的结果以在堆栈上初始化一个变量?
// Lets assume that we have a much more complex function so that the compiler will not
// always decide to compile time evaluation automatically
constexpr int func( int i )
{
return i+2;
}
int main()
{
??? int i = func(8);
...
i = 9;
}
如果我们使用constexpr该变量是隐式的 const 并且constinit在这里是不允许的。是否有机会使用函数的编译时间评估结果初始化此 var 而constexpr不会使其成为 const?我只是想知道为什么constinit仅限于静态变量。对我来说没有多大意义。