c++ - Why was the restriction on the comma operator being in a constant expression removed in C++11? -
recently when answering question realized comma operator allowed in constant expression in c++11 long expression surrounded ()
, example:
int a[ (1, 2) ] ;
pre c++11 forbidden use comma operator in constant expression, draft pre c++11 standard section 5.19
constant expressions says (emphasis mine):
[...]in particular, except in sizeof expressions, functions, class objects, pointers, or references shall not used, , assignment, increment, decrement, function-call, or comma operators shall not used.
why comma operator not allowed in constant expression pre c++11 , why restriction lifted?
we can find answer in std-discussion group comma operator in constant-expression thread gabriel dos reis says:
for c++11 proposed allow because restriction appeared arbitrary , reasons i've heard rationale ban appear unconvincing , specious me.
and richard smith earlier in thread notes of uses of comma operator in constant expression in both c++11 , c++14:
i disagree argument , conclusion. in c++11, comma operator useful within constexpr functions, because aren't allowed multiple statements:
template<typename t> constexpr t my_array<t>::at(size_type n) { return (n < size() || throw "n large"), (*this)[n]; }
in c++14, it's useful in of cases it's useful outside of constant expressions:
constexpr void do_stuff(int x[]) { (int = 0, j = 100; != j; ++i, --j) x[i] = x[j]; }
more philosophically, shouldn't ban things constant expressions because we're not imaginative enough find cases they're genuinely useful. constant expressions should not semi-random sublanguage of c++, missing random features, extent can avoid that. these days, top-level commas prohibited because constant-expressions tend occur in contexts comma mean else.
note argued c++11 example not correct since the expression containing comma operator should in ()
example gives essence of argument. argument based on grammar section 5.19
constant expressions:
constant-expression: conditional-expression
we can not comma operator conditional-expression can primary-expression gets ( expression )
, can comma operator expression.
t.c. points out may not case since relevant section seems vague on point.
Comments
Post a Comment