A typical function template signature:
template<typename Iterator, typename T>
T fn(Iterator first, Iterator last, T init)
{
T result;
// ...
return result;
}
The problem is, when I call it like this:
std::vector<long> data(1000,1);
fn(data.begin(), data.end(), 0);
or any other way without explicitly calling
fn<std::vector<long>::iterator, long>(data.begin(), data.end(),0);
then the type of T is an int
, and there is a risk of overflow and bad results in fn
.
So how do I specialize fn
so that the call to
fn(data.begin(), data.end(), 0);
is unambigous and results in T
to be set to Iterator::value_type
? The choice
template<Iterator>
typename iterator_traits<Iterator>::value_type fn(Iterator first, Iterator last, typename iterator_traits<Iterator>::value_type init)
{
//...
}
results in an ambiguous call error from g++/clang++.
EDIT:
I see my mistake now and the above code works with @Lightness Races suggestion below. Thanks for the help.