使用variadic-template函数计算多个值的平均值

Cor*_*mer 2 c++ average variadic-templates c++11

我正在尝试编写一个函数来确定任意数量的参数的平均值,所有这些参数都具有相同的类型.出于学习目的,我试图使用可变参数模板函数来做到这一点.

这是我到目前为止:

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)
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译它(使用MS Visual Studio 2013)时,我收到以下编译错误:

error C3520: 'args' : parameter pack must be expanded in this context (test.cpp)
Run Code Online (Sandbox Code Playgroud)

我该如何正确"解包" args参数包?我认为这是省略号的目的.

Dra*_*rax 7

您可以在参数包扩展周围添加花括号:

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)
}
Run Code Online (Sandbox Code Playgroud)

这应该创建一个std::initializer_list你可以使用基于范围的循环.