简体   繁体   中英

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?

Details: I am using C++20, and I have the following code:

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. 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.

I would like to combine the above two: to have diag executed in compile time, but keep M mutable; basically to compile-time initialize a non-const variable with something complex, like the return value of 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. 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.

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?

Note: In the above example code, diag creates a diagonal matrix with given entries. 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.

You might use intermediate constexpr variable:

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

You might wrap it in lambda:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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