C++ 具有编译时计算全局变量的功能

C++ Have function on compile time calculate global variables

我有 3 个全局变量,我希望在编译时计算它们,而无需先获取结果并手动分配全局变量。

我目前设置它的方式是有一个名为 Init() 的函数,它简单地计算 3 个变量,并且这个 Init() 函数在 Main 的顶部附近被调用。 我尝试做的是将 constexpr 添加到函数的前面,但在调用 Init() 之前打印值只是将变量设为 0.

什么是最好的方法,如果有的话,在编译时在下面的代码 运行 中使用函数 Init() 并且在程序开始时已经计算了 3 个全局变量。

示例代码:

static const int length = 8;
static const int seed = 40;

long long key1, key2, key3; // I want these to be calculated at compile-time instead of run-time if possible

void Init() {
    key1 = pow(seed, length);
    key2 = key1 * seed;
    key3  = key2 * seed;
}

...
void main(int argc,char * argv[]) {
    Init();
    ...
}

编辑:

我做了类似下面的事情,并且似乎已经奏效了,因为我可以在 main 的顶部打印出这些值: 有什么我可以做的来改进或缩短代码量吗?

constexpr long long calcKey1() {
    long long key1 = 1;
    for (int i = 0; i < length - 2; i++)
        key1 *= seed;

    return key1;
}

constexpr long long calcKey2(const long long key1) {
    return key1* seed;
}

constexpr long long calcKey3(const long long key2) {
    return key2 * seed;
}

constexpr long long key1 = calcKey1();
constexpr long long key2 = calcKey2(key1);
constexpr long long key3 = calcKey3(key2);

你要的是用constexpr。但它并不总是有效。

通常 std::pow 不是 constexpr (https://en.cppreference.com/w/cpp/numeric/math/pow)。

如果你真的想要编译时计算,你需要自己实现这些缺失的函数constexpr。的确,标准库一般不会constexpr,所以它仍然会在运行时做一些事情。查看 https://www.youtube.com/watch?v=CRDNPwXDVp0&frags=pl%2Cwn 了解更多关于未来的信息。