Return type of generic function

I want to write a generic function where I can specify the return type like float, double... but get the following errors.
I am using VS 2017 CE

E0304	no instance of function template "average" matches the argument list	
Generic_Algorithms_CPP Generic_Algorithms_CPP\Generic_Algorithms_CPP.cpp	25	

Error	C2672	'average': no matching overloaded function found
Generic_Algorithms_CPP	generic_algorithms_cpp.cpp 25	

Error	C2783	'ReturnType average(Iter,Iter)': could not deduce template argument for 
'ReturnType'	Generic_Algorithms_CPP	generic_algorithms_cpp.cpp 25	



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <iomanip>
#include <vector>

using namespace std;

template<class Iter, class ReturnType>
ReturnType average(Iter first, Iter last)
{
  ReturnType sum = ReturnType();
  size_t count = 0;

  while (first != last)
  {
    ++count;
    sum += *first;
    ++first;
  }
  return sum / count;
}

int main()
{
  vector<int> numbers = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
  double avg = average<double>(numbers.begin(), numbers.end());

  cout <<  setprecision(10) << "Avg = " << avg << '\n';
}

What's the proper way to do this?
Last edited on
> average<double>
The thing between the < > needs to match your template.
template<class Iter, class ReturnType>

So perhaps
double avg = average<vector<int>::iterator,double>(numbers.begin(), numbers.end());
Thanks, that works.
You can also just let Iter be inferred.

1
2
3
4
5
6
7
8
template <typename ReturnType, typename Iter>
ReturnType average(Iter first, Iter last) {
  // ...
}

// ...

double avg = average<double>(numbers.begin(), numbers.end());
Thanks TwilightSpectre ,
that's even better.
Topic archived. No new replies allowed.