【发布时间】:2018-11-24 23:56:29
【问题描述】:
在下面的代码中,VS2017 出现“错误 C3615: constexpr function 'to_array' cannot result in a constant expression' 编译器错误:
#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;
}
如果理论上是std::array can be 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;
}
EDIT2:
循环的完整错误信息是:
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'
【问题讨论】:
标签: c++