Search code examples
c++initializationoperator-overloadingeigen

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.


Solution

  • 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 <<.