In this answer I wrote the C++17 code:
cout << accumulate(cbegin(numbers), cend(numbers), decay_t<decltype(numbers[0])>{});
This received some negative commentary about the nature of C++'s type association, which I'm sad to say that I agree with :(
decay_t<decltype(numbers[0])>{}
is a very complex way to get a:
Zero-initialized type of an element of
numbers
Is it possible to maintain the association with the type of numbers
' elements, but not type like 30 characters to get it?
EDIT:
I've got a lot of answers involving the a wrapper for either accumulate
or for extracting the type from numbers[0]
. The problem being they require the reader to navigate to a secondary location to read a solution that is no less complex than the initialization code decay_t<decltype(numbers[0])>{}
.
The only reason that we have to do more than this: decltype(numbers[0])
Is because the array subscript operator returns a reference:
error: invalid cast of an rvalue expression of type 'int' to type 'int&'
It's interesting that with respect to decltype
's argument:
If the name of an object is parenthesized, it is treated as an ordinary lvalue expression
However, decltype((numbers[0]))
is still just a reference to an element of numbers
. So in the end these answers may be as close as we can come to simplifying this initialization :(