不能在 C++ 中使 std::array 成为 constexpr

Ale*_*sky 2 c++

在下面的代码中,我在 VS2017 中收到“错误 C3615:constexpr 函数 'to_array' 无法导致常量表达式”编译器错误:

#include <stdio.h>
#include <array>

template <typename T>
static constexpr std::array<std::uint8_t, sizeof(T)> to_array(T value)
{
    std::array<std::uint8_t, sizeof(T)> result {};

    for (std::size_t i{ sizeof(T) }; i != 0 ; --i)
    {
        result[i - 1] = static_cast<uint8_t>(value >> ((sizeof(T) - i) * 8));
    }

    return result;
}

int main()
{
    constexpr uint64_t sample = UINT64_C(0xab28ecb46814fe75);

    //error C3615: constexpr function 'to_array' cannot result in a constant expression
    constexpr auto a = to_array(sample);

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

如果理论上std::array 可以是 constexpr,为什么我会在这里收到错误?

编辑1:

它在没有循环的情况下编译:

template <typename T>
static constexpr std::array<std::uint8_t, sizeof(T)> to_array(T value)
{
    std::array<std::uint8_t, sizeof(T)> result {};

    //this is OK
    return result;
}
Run Code Online (Sandbox Code Playgroud)

编辑2:

循环的完整错误消息是:

error C3615: constexpr function 'to_array' cannot result in a constant expression
note: failure was caused by an uninitialized variable declaration
note: see usage of 'result'
Run Code Online (Sandbox Code Playgroud)

Rei*_*ica 5

如果理论上std::array 可以是 constexpr,为什么我会在这里收到错误?

您所提供的链接是处理构建一个std::array作为的一部分constexpr,而不是做别的吧,像你一样。

它在没有循环的情况下编译

您的错误与循环本身没有任何关系,因为它直接与在函数体内使用operator[]of 相关。std::arrayconstexpr

operator[]std::array constexpr,因为C ++ 17,但它似乎MSVC 19还没有实现它,虽然它在规格均匀。因此,在您的情况下,启用 C++17 的构建(编译器标志/std:c++latest)不会直接解决问题:-(

好消息是MSVC 20 符合标准:-)