A template function I have written has the following signature:
template<class IteratorT>
auto average(IteratorT& begin, IteratorT& end) -> decltype(*begin)
I thought that this would work fine, but apparently it doesn’t. I call the function by passing in pointers to the beginning and end of an array:
int integers[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
auto average = sigma::average(&integers[0], &integers[8]);
But clang tells me that it cannot find a matching function:
error: no matching function for call to ‘
average‘
What have I done wrong?
The problem is that the expression
&integers[0]returns an rvalue which cannot be bound to non-const reference parameters ofaveragetemplate function.So the solution is to make the parameters non-reference (removed
&):Then call it as (although it is not that important, but
&integers[8]seems to invoke undefined behavior, pedantically speaking):But why do you need such a function template to begin with? You could use
std::accumulateas: