局部常量不是constexpr可评估的,但无法弄清楚为什么

ori*_*and 2 c++ visual-c++ constexpr c++17

我正在尝试将一个int作为参数并单独对其字节进行操作,例如,采用0xDEADF00D并一一处理每个字节:0xDE 0xAD 0xF0 0x0D

为此,我完成了以下代码:

template <int state, int seed>
constexpr static uint32_t CalculateRandomFromState()
{
    const char bytes[4] = {
        (state >> 24) & 0xFF,
        (state >> 16) & 0xFF,
        (state >> 8) & 0xFF,
         state & 0xFF,
    };

    constexpr auto value = Compiletime::Hash<seed, sizeof(bytes)>(bytes);

    return value;
}
Run Code Online (Sandbox Code Playgroud)

HashFn的信号为:

template <const uint32_t seed, const uint32_t size = NULL>
constexpr uint32_t Hash(const char* message)
Run Code Online (Sandbox Code Playgroud)

编译因以下原因而失败:

错误C2131:表达式未求值为常数

注意:失败是由于在其生命周期之外读取变量导致的

注意:请参阅“字节”的用法

我已经在StackOverflow上阅读了有关参数可能无法在编译时进行评估的主题,(这就是为什么我将大多数参数切换为模板变量的原因,因此100%确保了它们在编译时),但是在这种情况下,它不会为何给出错误似乎是合乎逻辑的。该bytes值取决于编译时间值,字节也是一个常数。

为什么会超出使用寿命?如果我说"somestring"而不是变量,bytes那么它可以完美编译。这里有什么不可以持续评估的?

rus*_*tyx 7

constexpr on a function declaration does not require all evaluation paths to lead to a constant expression. Whether or not the result of a function call is constexpr can depend on the input arguments.

Assuming your Hash function looks like this:

template <uint32_t seed, uint32_t size>
constexpr uint32_t Hash(const char* message)
{
    uint32_t rc = seed;
    for (uint32_t i = 0; i < size; ++i)
        rc += message[i];
    return rc;
}
Run Code Online (Sandbox Code Playgroud)

This will evaluate to a constant expression iff message is a constant expression.

But you're invoking it with a non-constant expression:

    const char bytes[4] = {
        (state >> 24) & 0xFF,
        (state >> 16) & 0xFF,
        (state >> 8) & 0xFF,
         state & 0xFF,
    };

    constexpr auto value = Compiletime::Hash<seed, sizeof(bytes)>(bytes);
Run Code Online (Sandbox Code Playgroud)

Every time Hash(bytes) is called, bytes will potentially have a different address.

You can make it work by simply declaring bytes constexpr:

template <int state, int seed>
constexpr static uint32_t CalculateRandomFromState()
{
    constexpr char bytes[4] = {
        (state >> 24) & 0xFF,
        (state >> 16) & 0xFF,
        (state >> 8) & 0xFF,
         state & 0xFF,
    };

    constexpr auto value = Compiletime::Hash<seed, sizeof(bytes)>(bytes);

    return value;
}
Run Code Online (Sandbox Code Playgroud)