2

I just want to know if we can give two or more parameters to an overload of operator <<

An example will be more explicit:

anyType         operator<<(arg p1, arg p2)
{
DoSomethingWith(p1);
DoSomethingWith(p2);
return (*this);
}

And use it like this:

anyVar << anyVar2, anyVar3;
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
taof
  • 23
  • 4
  • Note: Your example is using two operators (operator << and operator , (comma)) –  Dec 13 '14 at 15:02

2 Answers2

5

No, that is not possible.

The closest you can come would be something like:

anyType         operator<<(std::pair<arg, arg> p)
{
  DoSomethingWith(p.first);
  DoSomethingWith(p.second);
  return (*this);
}

anyvar << std::make_pair(a1, a2);

Alternatively, you could do something much more complicated to effectively curry the call to your operator, by having anyType::operator<<(arg) return a temporary object which just holds on to its argument and implements a different tempObject::operator<<(arg) which actually does the work. You can then call that as anyvar << arg1 << arg2. I really doubt whether it is worth the trouble, aside from being a learning experience.

Something similar to that style is often used in the "builder" pattern, but using member functions rather than an explicit operator. That's useful because you can arrange to effectively make configuration arguments order-independent.

rici
  • 234,347
  • 28
  • 237
  • 341
  • Thanks you ! I think i will do with the std::pair, it's a bit tricky but looks good to me – taof Dec 13 '14 at 15:10
  • 1
    I think at this point it might be wise to ask *why* you think the `<<` operator is the correct choice of function overload for this behaviour. non-standard operator overloading is very difficult to maintain and debug. – Richard Hodges Dec 13 '14 at 15:47
0

No, you can't do that. A binary operator can only be overloaded to take two operands, either as a member function with one parameter, or (except for assignment operators) a non-member with two.

If you want something that behaves more like a function, write a function.

Alternatively, you could write your operator to allow chaining, just as the standard overloads for I/O streams do:

anyType & operator<<(arg p) {   // return a reference, not a copy
    DoSomethingWith(p);
    return *this;
}

anyvar << anyVar2 << anyVar3;  // Does the thing to each variable, in turn.
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Ok thanks you ! But i don't give a good explain, i want to do different things with p1 and p2, so i can't do like that. I will do like Rici say, with a std::pair, or like you say, simply with a function – taof Dec 13 '14 at 15:09