Uses of C comma operator [duplicate]

2018-12-31 14:56发布

This question already has an answer here:

You see it used in for loop statements, but it's legal syntax anywhere. What uses have you found for it elsewhere, if any?

20条回答
怪性笑人.
2楼-- · 2018-12-31 15:48

Two killer comma operator features in C++:

a) Read from stream until specific string is encountered (helps to keep the code DRY):

 while (cin >> str, str != "STOP") {
   //process str
 }

b) Write complex code in constructor initializers:

class X : public A {
  X() : A( (global_function(), global_result) ) {};
};
查看更多
墨雨无痕
3楼-- · 2018-12-31 15:48

The Boost Assignment library is a good example of overloading the comma operator in a useful, readable way. For example:

using namespace boost::assign;

vector<int> v; 
v += 1,2,3,4,5,6,7,8,9;
查看更多
登录 后发表回答