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 :(
While I would always choose to write a helper function as per @Barry, if numbers is a standard container, it will export the type value_type, so you can save a little complexity:
going further, we could define this template function:
which gives us this:
Personal preference: I find the
decay_t
,decltype
anddeclval
dance pretty annoying and hard to read.Instead, I would use an extra level of indirection through a type-trait
value_t<It>
and zero-initialization throughinit = R{}
I think the best you can do is just factor this out somewhere:
Or more generally:
where
adl_begin
is a version ofbegin()
that accounts for ADL.Sure, we technically still have all the cruft that you were trying to avoid earlier... but at least now you never have to look at it again?