Is it possible to call the << operator using prefix notation?

90 views Asked by At

I am wondering if I could write, for instance: <<(object, cout); or <<(cout,object); where object is a user defined class which has the << operator overloaded, just as one could write: int a = +(2,3); and obtain the expected result, as in int a = 2 + 3;. Furthermore, what should one do if this is possible, but requires a few steps? Should one overload the << operator with two different signatures?

2

There are 2 answers

2
Ardent Coder On

just as one could write: int a = +(2,3); and obtain the expected result, as in int a = 2 + 3;

No, you have a misunderstanding. +(2, 3) will go by the associativity of the comma operator and assign +3 (3) to the variable a.

Therefore, int a = +(2, 3) is the same as int a = 3, and not int a = 2 + 3

I am wondering if I could write, for instance: <<(object, cout); or <<(cout,object);

No, you can't.

If you want to use the operators in that fashion then you should call its fully qualified name, for example:

operator+ instead of +

operator<< instead of <<

Note:

This will not work for fundamental datatypes. Take care of the class scope and namespaces when you are using the overloaded versions of these operators.

11
cigien On

You can do this, e.g.

operator<<(std::cout, "hi");

This expression

int a = +(2, 3);

is not doing operator+. It's first applying the , sequence operator, which gives 3, and then applying unary +, which gives 3.

You can't do this

int a = operator+(2, 3); // error

because ints are fundamental types.

If you have user defined types S, then the following snippets have the same meaning

S s{};
std::cout << s;
auto x = s + s;

is the same as

S s{};
operator<<(std::cout, s);
auto x = operator+(s, s);

assuming the operators are defined for S, the correct operator will be called.