我正在尝试编写一个函数来确定任意数量参数的平均值,其中所有参数都具有相同的类型。出于学习目的,我正在尝试使用可变模板函数来实现。
以下是我的代码:
我应该如何正确“解包”
以下是我的代码:
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
参数包?我认为这就是省略号的目的。
double test = Mean<int>(5, 10, 50);
,这样你就不需要指定结果类型了。你可以修改这个函数的方式,使其不必指定结果类型,但这取决于你的用例(你可能总是想要整数、双精度浮点数或者总是想要第一个参数的类型等等)。我觉得这是最通用的方法,因为它将选择权留给了函数的使用者。 - Drax