static函数内部不允许使用变量constexpr。这是有道理的,因为static会给一个应该是纯函数的状态引入一个状态。
但是,我不明白为什么我们不能在函数中包含static constexpr变量。constexpr保证始终具有相同的值,因此该函数将保持纯净。
我为什么要在乎?因为static在运行时会有所作为。考虑这段代码:
#include <array>
constexpr int at(const std::array<int, 100>& v, int index)
{
return v[index];
}
int foo1(int i) {
static constexpr std::array<int, 100> v = {
5, 7, 0, 0, 5 // The rest are zero
};
return at(v, i);
}
constexpr int foo2(int i) {
constexpr std::array<int, 100> v = {
5, 7, 0, 0, 5 // The rest are zero
};
return at(v, i);
}
int foo2_caller(int i) {
return foo2(i);
}
直播:https ://gcc.godbolt.org/z/umdXgv
foo1有 3 个 asm 指令,因为它将缓冲区存储在静态存储中。Whilefoo2有 15 个 asm 指令,因为需要在每次调用时分配和初始化缓冲区,而编译器无法对此进行优化。
请注意,foo1此处仅显示foo2. 我想编写一个可以在编译和运行时使用的函数。这就是背后的想法foo2。但是我们看到它不能像 runtime-only 那样高效foo1,这令人不安。
我发现的唯一有意义的相关讨论是 this,但没有static constexpr具体讨论。
问题是:
- 我的推理是否正确,还是我错过了
static constexpr变量可能导致的一些问题? - 有没有解决这个问题的建议?