简体   繁体   English

编译时初始化一个非常量变量

[英]Compile-time init a NON constant variable

Question: How do I compile-time initialize a non-constant variable with a function while still enabling a runtime call to said function?问题:如何在编译时使用 function 初始化非常量变量,同时仍然启用对所述 function 的运行时调用?

Details: I am using C++20, and I have the following code:详细信息:我正在使用 C++20,并且我有以下代码:

template<typename T>
constexpr auto diag(auto&&.. vals) {...}
// ...
constexpr auto M = diag<double>(1,2,3);

A expected, the above code compiles, diag is executed in compile-time, and M is constant. A 预期,上述代码编译,diag 在编译时执行,M 为常量。 If I change the calling line to如果我将呼叫线路更改为

auto M = diag<double>(1,2,3);

the code again, compiles, but this time, diag is executed in runtime, and M is not constant.代码再次编译,但这次 diag 在运行时执行,并且 M 不是常量。

I would like to combine the above two: to have diag executed in compile time, but keep M mutable;我想将以上两者结合起来:在编译时执行 diag,但保持 M 可变; basically to compile-time initialize a non-const variable with something complex, like the return value of diag.基本上是在编译时用一些复杂的东西初始化一个非常量变量,比如 diag 的返回值。

Approach : I change the code to方法:我将代码更改为

template<typename T>
consteval auto diag(auto&&.. vals) {...}
// ...
auto M = diag<double>(1,2,3);

This time, M is non-constant, and diag is executed in compile-time, so effectively my goal is achieved.这一次,M 是非常量的,而 diag 是在编译时执行的,所以我的目标有效地实现了。 My problem is: consteval must be executed in compile-time, so if I want to use diag somewhere else in the code in runtime, I'll have to write another function.我的问题是: consteval必须在编译时执行,所以如果我想在运行时代码的其他地方使用 diag,我将不得不编写另一个 function。

This leads to the Question: How do I compile-time initialize a non-constant variable with a function while still enabling a runtime call to said function?这导致了一个问题:如何在编译时使用 function 初始化非常量变量,同时仍然启用对所述 function 的运行时调用?

Note: In the above example code, diag creates a diagonal matrix with given entries.注意:在上面的示例代码中,diag 创建了一个具有给定条目的对角矩阵。 I want the code to be equivalent to我希望代码等效于

Matrix<double, 3, 3> M = { {1.0,0.0,0.0}, {0.0,2.0,0.0}, {0.0,0.0,3.0}};

Here, M is not a constant, but it is assigned from a constant, compile-time determined diagonal matrix.这里,M 不是一个常数,而是从一个常数的、编译时确定的对角矩阵分配的。

You might use intermediate constexpr variable:您可以使用中间constexpr变量:

constexpr auto MInit = diag<double>(1,2,3);
auto M = MInit;

You might wrap it in lambda:您可以将其包装在 lambda 中:

auto M = [](){ constexpr auto MInit = diag<double>(1,2,3); return MInit; }();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM