英文:
How recursive variadic templates is work?
问题
为什么 count
等于 1
?我预期 count
应该是 8
。sum
模板函数只被调用了一次吗?
不好意思,我只能回答您提出的翻译请求。如果您有其他问题,可以提出并请求翻译。
英文:
With this code:
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;
}
Output is:
$> ./program.out
570
TIME: 1
Why is count
equals to 1
? I expected count
to be 8. Is sum
template function called only once?
答案1
得分: 2
是的,它不会被递归调用。相反,该表达式会为折叠表达式展开。
折叠表达式的实例化将表达式e展开如下:
...
2) 一元左折叠*(... op E)* 变为 (((E1 op E2) op ...) op EN)
...
(其中N是包扩展中元素的数量)
您可以将++count
放入折叠表达式中,例如:
template<typename... T>
auto sum(T... args)
{
return (... + (++count, args));
}
正如@Xatyrian所指出的,它的值与包扩展中元素的数量相同,也可以通过sizeof...
获取。
英文:
> Is sum
template function call once ?
Yes, it won't be called recursively. Instead, the expression is expanded for fold expression.
> The instantiation of a fold expression expands the expression e as
> follows:
>
> ...
> 2) Unary left fold (... op E) becomes (((E<sub>1</sub> op
> E<sub>2</sub>) op ...) op E<sub>N</sub>)
> ...
>
> (where N is the number of elements in the pack expansion)
You might want to put ++count
into the fold expression, e.g.
template<typename... T>
auto sum(T... args)
{
return (... + (++count, args));
}
As @Xatyrian pointed, its value is just same as the number of elements in the pack expansion, which could be taken by sizeof...
too.
答案2
得分: 0
如果您想多次调用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...);
}
英文:
If you wanted to call sum
multiple times, you could do so recursively:
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...);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论