Question

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?

Was it helpful?

Solution

The problem is that the expression&integers[0] returns an rvalue which cannot be bound to non-const reference parameters of average template function.

So the solution is to make the parameters non-reference (removed &):

template<class IteratorT>
auto average(IteratorT begin, IteratorT end) -> decltype(*begin)

Then call it as (although it is not that important, but &integers[8] seems to invoke undefined behavior, pedantically speaking):

auto average = sigma::average(integers, integers + 8);

But why do you need such a function template to begin with? You could use std::accumulate as:

#include <algorithm> //must include this

auto average = std::accumulate(integers, integers + 8, 0)/8;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top