I am getting 'error C3615: constexpr function 'to_array' cannot result in a constant expression' compiler error with VS2017 in the code below:
#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;
}
If theoretically std::array can be constexpr, why am I getting the error here?
EDIT1:
it compiles without the loop:
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:
the full error message with the loop is:
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'