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

前端 未结 3 1738
夕颜
夕颜 2020-12-01 17:00

Here\'s a part of Eigen documentation:

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

Output:

         


        
3条回答
  •  萌比男神i
    2020-12-01 17:13

    The comma itself is an operator in c++ which can be overloaded (and apparently is by eigen). I don't know the exact way eigen implements the overloading but I am sure that you can search for the sources of eigen to look it up.

    To your little experient you have to understand how the unoverloaded comma operator works in c++.

    The comma operator has the form , and is evaluated to whatever the second statement is evaluated to. The operator << has a higher precedence than the operator ,. Because of that the cout is evaluated before the rest of the comma operations are evaluated.

    Because , is Left-to-right associative the code (1,2,3,4,5) is equal to ((((1,2),3),4),5) which evaluates to the most right value, which is 5.

提交回复
热议问题