c++ - 递归可变参数模板如何工作?

标签 c++ templates c++17 variadic-templates

使用此代码:

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/

相关文章:

c++ - 使用带有 std::void_t 的类模板检查默认构造函数

c++ - 这是缓存线程安全(c++)的通用实现吗?

c++ - 自动排除如何与带有嵌套小部件的 QRadioButtons 一起使用?

c++ - 我的运算符重载没有在我的 int main 中返回?

c++ - 为什么值放在 fortran 函数的数组中而不是在调用 c++ 函数中?

C++ 在扩展模板类时定义特定的对象类型

c++ - 有没有办法从字符串输出cout中的反斜杠符号?

c++ - 当参数不同时,重载解析不会选择模板

c++ - 如何为模板类型创建别名?

c++ - 如何设计一个 "Awaitable"基类?