Reputation: 967
I'd like to write a set of generic arithmetic functions that can act on any type that passes the is_arithmetic test. For example, this min function is ok:
template<typename T>
T min(std::vector<T> values)
{
T min = values.at(0);
for (T& value : values)
{
if (value < min) {
min = value;
}
}
return min;
}
But what about a function to average a vector of values:
template<typename T>
T average(std::vector<T> values)
{
long double sum = 0;
for (T& value : values)
{
sum += value;
}
return sum / values.size();
}
This obviously will not compile because generic types cannot interact with concrete types. In my case, the incoming type could be anything from int8 to double and I'd like to avoid writing essentially the same functions for each type. Is there an elegant solution to this problem?
Upvotes: 0
Views: 95
Reputation: 1551
Declare sum as T sum = 0;
and you'll have what you're looking for. If you need the sum to be of different type than the vector
holds, then use a second template parameter, e.g. template<class T, class U> U average(std::vector<T> values);
. You'll have to specify U
when you call the function, though.
Note - these are templates, not generics, and so it is absolutely fine to mix concrete types with templatized types -- although it will of course put constraints on what your template arguments can be.
Upvotes: 1