问题
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;
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/27460079/operator-with-multiple-parameters