【发布时间】:2014-07-29 17:06:29
【问题描述】:
我正在尝试编写一个函数来确定任意数量的参数的平均值,所有这些参数都具有相同的类型。出于学习目的,我尝试使用可变参数模板函数来做到这一点。
这是我目前所拥有的:
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)
}
当我尝试编译它(使用 MS Visual Studio 2013)时,我收到以下编译错误:
error C3520: 'args' : parameter pack must be expanded in this context (test.cpp)
我应该如何正确“解包”args 参数包?我认为这就是省略号的目的。
【问题讨论】:
标签: c++ c++11 average variadic-templates