Question

Take a look at this syntax :

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

The output:

1 2 3
4 5 6
7 8 9

How can i overload first << operator like this ?

Was it helpful?

Solution

Following may help you : https://ideone.com/Ap6WWt

template <typename T, int W, int H>
class MatrixStream
{
public:
    MatrixStream(Matrix<T, W, H>& mat, const T& value) : mat(mat), index(0)
    {
        *this, value;
    }

    MatrixStream& operator , (const T& value);
private:
    Matrix<T, W, H>& mat;
    int index;
};

template <typename T, int W, int H>
class Matrix
{
public:
    MatrixStream<T, W, H> operator << (const T& value) {
        return MatrixStream<T, W, H>(*this, value);
    }

    T m[W][H];
};

template <typename T, int W, int H>
MatrixStream<T, W, H>& MatrixStream<T, W, H>::operator , (const T& value)
{
    assert(index < W * H);
    int w = index / H;
    int h = index % H;
    mat.m[w][h] = value;
    ++index;
    return *this;
}

but overloading operator , is highly discouraged. As said in the comment, you may use as alternative m << {1, 2, 3, 4, 5, 6, 7, 8, 9} or m << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9. (the first one is cleaner IMHO).

OTHER TIPS

When you use an expression such as :

CleanInitArray a(6);
a = 1,2,3,4,5,6; 

It is read by the compiler like this:

((((((a=1),2),3),4),5),6);

Therefore you need to overload the assignment operator to return an array-like object and use that to overload the comma operator,.

The only useful application of overloading operator, I've ever seen in my whole C++ life was Boost.Assignment, and even this has become redundant in C++11, thanks to std::initializer_list.

Nevertheless, it cannot hurt to know how it works, so I suggest you just look at the Boost source code. It's open source, you can download it for free, and it's known to work as intended.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top