这已经是一个很好的答案,但是,当我尝试将参数作为 typename(不知道确切的词)执行相同操作时,它们传递了任意数量的参数作为参数,例如:
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>();
}
为什么那里有错误?有没有可能的修复?另外,我需要将参数作为类型名传递,而不是参数。
首先,“base”函数也需要是一个模板。
然后为了区分这两个模板,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...>();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句