I want to write a generic averaging algorithm. That is, for any type T that has an operator+ (T) and an operator/(float), I would like to find the average of T’s in a container:
Something like this works fine for float-ish types:
template<typename T>
typename T::value_type RunningAverage(const T& v)
{
typename T::value_type vectorRunningAverage = 0;
for(unsigned int i = 0; i < v.size(); ++i)
{
vectorRunningAverage = (v[i] + i*vectorRunningAverage)/(i+1);
}
return vectorRunningAverage;
}
I could change
typename T::value_type vectorRunningAverage = 0;
to
float vectorRunningAverage = 0;
and then it would work with a type like unsigned char (can’t add more than a few unsigned chars and store the result in an unsigned char without overflow) because it can be implicitly converted to float. However, if I have some more complicated types (say I want to average the components in a std::vector<std::vector<unsigned char> >, this doesn’t work. Is there something I’m missing? Or does it just not make sense to do this?
I think you should let the caller to explicitly mention the desired return type:
I also think you should take begin & end iterators rather than the entire container, as it will make your function more generic (you could then get the average of the front half of a vector, for example).