Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

How could comma separated initialization such as in Eigen be possibly implemented in C++?

Here's a part of Eigen documentation:

Matrix3f m;
m << 1, 2, 3,
     4, 5, 6,
     7, 8, 9;
std::cout << m;

Output:

1 2 3
4 5 6
7 8 9

I couldn't understand how could all the comma separated values be captured by operator<< above. I did a tiny experiment:

cout << "Just commas: ";
cout << 1, 2, 3, 4, 5;
cout << endl;
cout << "Commas in parentheses: ";
cout << ( 1, 2, 3, 4, 5 );
cout << endl;

Predictably (according to my understanding of C++ syntax) only one of the values was captured by operator<< :

Just commas: 1
Commas in parentheses: 5

Thus the title question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The basic idea is to overload both the << and the , operators.

m << 1 is overloaded to put 1 into m and then returns a special proxy object – call it p – holding a reference to m.

Then p, 2 is overloaded to put 2 into m and return p, so that p, 2, 3 will first put 2 into m and then 3.

A similar technique is used with Boost.Assign, though they use += rather than <<.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...