Is there away to achieve the behavior shown in the example (non compiling) code below? I (think I) understand why it doesn't compile given that the required calls to std::initializer_list functions are not constexpr.
The goal is to be able to create an array from a constant initialiser list when an additional element is appended to the end that is the sum of the preceeding elements.
All the posts I found on initialising arrays at compile time required lots of complex recursive template function calls and all were related to generating sequences of numbers.
#include <initializer_list>
#include <array>
template <typename T> constexpr auto CheckSummedArray(const std::initializer_list<T> & i)
{
std::array<T, i.size() + 1> res;
std::copy(i.begin(), i.end(), res.begin());
auto cs = T();
for (auto r : i)
{
cs += r;
}
res[res.size() - 1] = cs;
return res;
}
constexpr auto testArray = CheckSummedArray<int>({1,2,3,4});
static_assert(testArray.size() == 5);
static_assert(testArray[0] == 1);
static_assert(testArray[4] == 9);
-std=c++14or-std=c++17you are using?