Bob Maza
Bob Maza

Reputation: 59

c++11 specefic overload of << operator

For an assignment, i have to code a matrix class following some clear instructions. One of the instructions is overloading the << operator , so that we can read the values this exact way for a matrix m :

m << 1,2,3,4,5,6;

i tried looking into functions with variable parameters , but then i saw that i can't overload the operator with a variable number of parameters.

i tried looking in std::initializer_list , using some reference code from cpp reference

std::vector<float> mat;


Mat<M,N>& operator<<(std::initializer_list<float> l)
{
    this->mat.insert(this->mat.begin(),l.begin(),l.end());

    return *this;
}

so my question is, what class/type of parameters can i use to achieve this, the options that i thought of did not work , or maybe i did not use them the right way.

thank you very much.

EDIT : After the great answer from @bames53 i tried to incorporate and it works just great !

Upvotes: 0

Views: 51

Answers (1)

bames53
bames53

Reputation: 88155

<< has higher precedence than , so what your expression m << 1,2,3,4,5,6 does is:

((((((m << 1), 2), 3), 4), 5), 6)

In other words you need m << 1 to return an object representing the operation of having read in 1 and which is prepared to read in 2. This sort of thing is often done with something called 'expression templates' though in your case you don't really need templates.

Your usage will have one difference in that you do need to modify the object as you go along, whereas the usual expression templates operate lazily, waiting until their object is converted to the final result type before actually doing the work.

#include <iostream>

// a type to do something with
struct M { int i; };

// a type to represent the operations
struct Input_operation { M &m; int count; };


Input_operation operator << (M &m, int i) {
  m.i = i;
  return {m, 1};
}

Input_operation operator , (Input_operation op, int i) {
  op.m.i += i;
  op.count++;
  return op;
}

int main() {
  M m;
  m << 1, 2, 3, 4, 5, 6;
  std::cout << m.i << '\n';
}

Upvotes: 2

Related Questions