诸如 Eigen 中的逗号分隔初始化如何可能在 C++ 中实现?

这是 Eigen 文档的一部分:

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

输出:

1 2 34 5 67 8 9

我无法理解运算符如何捕获所有逗号分隔的值<<多于.我做了一个小实验:

cout <<只是逗号:";cout <<1、2、3、4、5;cout <<结束;cout <<括号中的逗号:";cout <<(1、2、3、4、5);cout <<结束;

可以预见(根据我对 C++ 语法的理解)只有一个值被 operator<<<:

只有逗号:1括号中的逗号:5

因此标题问题.

解决方案

基本思想是重载 <<, 运算符.p>

<代码>m <<1被重载将1放入m,然后返回一个特殊的代理对象–称之为 p –持有对 m 的引用.

然后p,2被重载将2放入m并返回p,这样p, 2, 3 会先将 2 放入 m 再放入 3.

类似的技术用于 Boost.Assign,尽管他们使用 += 而不是 <<.

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.

解决方案

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

相关文章