Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`operator<<` on comma separated values in C++

The following syntax is working in OpenCV

Mat R = (Mat_<double>(4, 4) <<
        1,          0,           0, 0,
        0, cos(alpha), -sin(alpha), 0,
        0, sin(alpha),  cos(alpha), 0,
        0,          0,           0, 1);

How it can be? What operator was overloaded? What is the sense of this expression? Does comma operator can be overloaded in nowadays C++?

like image 667
Suzan Cioc Avatar asked Jan 14 '23 04:01

Suzan Cioc


1 Answers

A comma operator can be overloaded, although it is typically not recommended (in many cases the overloaded comma is confusing).

The expression above defines 16 values for 4*4 matrix. If you are wondering how this is possible, I'll show a simpler example. Suppose we want to be able to write something like

MyVector<double> R = (MyVector<double>() << 1 , 2 , 3);

then we can define MyVector so that << and , operators append new value to the vector:

template<typename T> 
class MyVector: public std::vector<T> {
 public:
  MyVector<T>& operator << (T value) { push_back(value); return *this; }
  MyVector<T>& operator , (T value) { push_back(value); return *this; }
  ...
};
like image 184
nullptr Avatar answered Jan 22 '23 10:01

nullptr