使用此代码:
static unsigned count = 0;
template<typename... T>
auto sum(T... args)
{
++count;
return (... + args);
}
int main (void)
{
std::cout << sum(12, 32, 32, 12, 4, 3, 43, 432) << std::endl;
std::cout << "TIME: " << count << std::endl;
}
输出是:
$> ./program.out
570
TIME: 1
为什么count
等于1
?我预计 count
为 8。sum
模板函数只调用一次吗?
最佳答案
Is
sum
template function call once ?
是的,它不会被递归调用。相反,表达式会扩展为 fold expression 。
The instantiation of a fold expression expands the expression e as follows:
...
2) Unary left fold (... op E) becomes (((E1 op E2) op ...) op EN)
...(where N is the number of elements in the pack expansion)
您可能希望将 ++count
放入折叠表达式中,例如
template<typename... T>
auto sum(T... args)
{
return (... + (++count, args));
}
如@Xatyrian指出,它的值与包扩展中的元素数量相同,也可以通过 sizeof...
获取。
关于c++ - 递归可变参数模板如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59575635/