there is a little compiled code, but it worked with C ++ 11 and only deep recursion O (log (N)) is required.
template<typename Iterator >
constexpr size_t c_dist(Iterator first, Iterator last){ return (last - first); }
template< typename Iterator, typename U>
constexpr U c_accumulate(Iterator first, Iterator last, U u)
{
return (first == last)
? u
: c_dist(first , last) == 1
? ( u + *first )
:
c_accumulate(first, first + c_dist(first, last ) / 2, u ) +
c_accumulate(first + c_dist(first, last)/2, last, u);
}
constexpr int a[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21};
constexpr int sum = c_accumulate(a, a + sizeof(a)/sizeof(a[0]), 0);
static_assert(sum == 21*22/2, "!");
source
share