本文介绍了为什么编译器不能通过逗号运算符扩展可变参数模板的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们可以不要使用可变参数扩展,就像它是一个逗号运算符链。在该问题中,示例如下:

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

或类似这样:

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



我知道我们可以使用一些递归技巧来获得我们想要的, a href =http://stackoverflow.com/questions/12342633/how-do-i-play-out-the-arguments-of-a-function-using-a-variadic-template>喜欢这样
。我不知道为什么标准没有描述这样的行为?

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?

推荐答案

允许扩展包的其他上下文是列表,其中逗号是

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

例如, f(args ...)展开为函数参数列表 tuple< Args ...> 扩展为模板参数列表。

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

示例pack扩展形成语句,并且语句的子表达式之间的逗号是逗号运算符,可以重载,导致任意复杂的代码,并且与内置逗号运算符不同,不是强制左右对照评价。如果你的(std :: cout<< std :: forward< Args>(args))...; 例子写出了args未指定的顺序,因为参数包中的一个类型重载运算符< <运算符评论。

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.

不,它不会含糊不清。可以使用 f(++ args ...),它是明确和明确的。你的建议的困难不是如何解析 ++ args ... 这是将它扩展为包含逗号运算符的语句后会发生什么。

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.

这篇关于为什么编译器不能通过逗号运算符扩展可变参数模板的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:55