递归可变参数模板是如何工作的?

How recursive variadic templates is work?

使用此代码:

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));
}

正如指出的那样,它的值与包扩展中的元素数相同,sizeof...也可以取。

如果你想多次调用 sum,你可以递归地这样做:

static unsigned count = 0;

template <typename T>
auto sum(T t)
{
    ++count;
    return t;
}

template <typename T, typename... Ts>
auto sum(T t, Ts... ts)
{
    ++count;
    return t + sum(ts...);
}