c++ - 为什么在 C++11 中取消了对逗号运算符在常量表达式中的限制?

标签 c++ c++11 language-lawyer c++03 constant-expression

最近当answering a question我意识到 C++11 中的常量表达式中允许使用 逗号运算符只要表达式被()包围,例如:

int a[ (1, 2) ] ;

Pre C++11禁止在常量表达式中使用 逗号运算符,来自 C++11 标准草案前的标准部分 5.19 常量表达式,它说( 强调我的):

[...]In particular, except in sizeof expressions, functions, class objects, pointers, or references shall not be used, and assignment, increment, decrement, function-call, or comma operators shall not be used.

为什么在 C++11 之前的常量表达式中不允许使用逗号运算符,为什么取消了这个限制?

最佳答案

我们可以在 std-discussion 中找到答案。群Comma operator in constant-expression Gabriel Dos Reis 说的线程:

For C++11 I proposed to allow it because the restriction appeared arbitrary and all reasons I've heard as rationale for its ban appear very unconvincing and specious to me.

和理查德·史密斯 earlier in the thread说明了 C++11 和 C++14 中 常量表达式逗号运算符 的一些用法:

I disagree with your argument and your conclusion. In C++11, the comma operator is useful within constexpr functions, because we aren't allowed multiple statements:

template<typename T>   constexpr T my_array<T>::at(size_type n) {
  return (n < size() || throw "n too large"), (*this)[n];   }

In C++14, it's useful in essentially all of the cases where it's useful outside of constant expressions:

constexpr void do_stuff(int x[]) {
  for (int i = 0, j = 100; i != j; ++i, --j)
    x[i] = x[j];   }

More philosophically, we shouldn't ban things from constant expressions simply because we're not imaginative enough to find the cases where they're genuinely useful. Constant expressions should not be a semi-random sublanguage of C++, missing random features, to the extent that we can avoid that. These days, top-level commas are prohibited mostly because constant-expressions tend to occur in contexts where a comma would mean something else.

请注意,有人认为他的 C++11 示例不正确,因为包含 逗号运算符 的表达式应该在 () 中,但他的示例给出了本质的论点。该参数将基于 5.19 常量表达式 部分的语法:

constant-expression:
   conditional-expression

我们不能从 conditional-expression 得到 comma operator 但我们可以得到 primary-expression 这让我们得到 ( 表达式 ) 然后我们可以从 表达式 得到 逗号操作符

T.C. points out可能并非如此,因为相关部分在这一点上似乎含糊不清。

关于c++ - 为什么在 C++11 中取消了对逗号运算符在常量表达式中的限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27324573/

相关文章:

c++ - vim 有 C++11 语法文件吗?

c++ - 运行时函数在编译时函数上分支?

c++ - 在线程之间创建 'synchronization point'

c++ - libpq - 编写测试

c++ - C++中按引用和值传递

c - 分配对象和结构的有效类型

c - "cast specifies a conversion"是什么意思?

c++ - 使 C++ 中的重载成员访问运算符返回临时值

c++11 - 作为可变参数模板参数的成员指针

c++ - 友元函数的参数依赖查找