Why can't compilers expand arguments of a variadic template via comma operator?

China☆狼群 提交于 2019-12-10 15:31:56

问题


I know that we can't use variadic expansions as if it is a chain of comma operators. In that question the sample is like this:

template<typename... Args>
inline void increment_all(Args&... args) 
{
    ++args...; 
}

It might be ambiguous either to increment or expand first so parentheses won't hurt:

template<typename... Args>
inline void increment_all(Args&... args)
{
    (++args)...; 
}

or something like this:

template<typename... Args>
void cout_all(Args&&... args)
{
    (std::cout << std::forward<Args>(args))...; 
}

I know that we can use some recursion tricks to get what we want, like this. What I don't know is why does not the standard describe such behavior? I mean, what is the reason behind it?


回答1:


The other contexts where a pack expansion is allowed are lists where a comma is a separator between list elements, not an operator.

For example, f(args...) expands to a function argument list, tuple<Args...> expands to a template argument list.

In your examples the pack expansion forms a statement, and commas between sub-expressions of a statement are the comma operator, which could be overloaded, leading to arbitrarily complicated code, and unlike the builtin comma operator, not forcing left-to-right evaluation. You'd be surprised if your (std::cout << std::forward<Args>(args))...; example wrote out the args in unspecified order because one of the types in the parameter pack overloaded operator<< and operator, and broke the order of evaluation.

Doing this would not be a simple extension to the current rules, it would be a completely different context with very different effects.

It might be ambiguous either to increment or expand first so parentheses won't hurt:

No, it wouldn't be ambiguous. It's OK to use f(++args...) and it's clear and unambiguous. The difficulty with your suggestion is not how to parse ++args... it's what happens after you expand it to a statement containing comma operators.



来源:https://stackoverflow.com/questions/14430290/why-cant-compilers-expand-arguments-of-a-variadic-template-via-comma-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!