This已经是一个很好的答案,但是,当我尝试将参数作为类型名(不知道确切的词)做同样的事情时,他们传递了任意数量的参数作为参数,例如:
int sum=0;
int func()
{
return sum;
}
template <int first, int ... rest>
int func()
{
sum += first;
return func(rest...); //Error C2660 'func': function does not take 4 arguments
/*
return func<rest...>(); this also doesn't work: Error 'int func(void)': could not deduce template argument for 'first' and 'func': no matching overloaded function found
*/
}
int main()
{
cout << func<1,2,3,4,5>();
}
为什么那里有错误?有什么可能的修复方法吗?此外,我需要将参数作为类型名称而不是参数传递。
最佳答案
首先,“基础”函数也需要是一个模板。
那么为了区分这两个模板,parameter-pack 模板需要至少接受两个模板参数。
最后,您可以不用全局 sum
变量来解决这个问题,而是使用 return
语句中的加法。
综合起来:
template <int first>
int func()
{
return first;
}
template <int first, int second, int ...rest>
int func()
{
return first + func<second, rest...>();
}
关于c++ - 如何从 Variadics 模板获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68986479/