CoryKramer CoryKramer - 3 months ago 17
C++ Question

Calculate the average of several values using a variadic-template function

I am trying to write a function to determine the average of an arbitrary number of arguments, all of which have the same type. For learning purposes I am trying to do this using a variadic-templated function.

This is what I have so far:

template<typename T, class ... Args>
T Mean(Args ... args)
{
int numArgs = sizeof...(args);
if (numArgs == 0)
return T(); // If there are no arguments, just return the default value of that type

T total;
for (auto value : args...)
{
total += value;
}

return total / numArgs; // Simple arithmetic average (sum divided by total)
}


When I try to compile this (using MS Visual Studio 2013) I get the following compilation error:

error C3520: 'args' : parameter pack must be expanded in this context (test.cpp)


How should I properly "unpack" the
args
parameter pack? I thought that was the purpose of the ellipses.

Answer
template<typename T, class ... Args>
T Mean(Args ... args)
{
    int numArgs = sizeof...(args);
    if (numArgs == 0)
        return T();           // If there are no arguments, just return the default value of that type

    T total;
    for (auto value : {args...})
    {
        total += value;
    }

    return total / numArgs;   // Simple arithmetic average (sum divided by total)
}

This should create an std::initializer_list on which you can then use range-based for loops.