Search code examples
c++streamoperator-keywordputternary

Ternary Put Operator in cpp possible?


I was thinking about implementing a ternary put operator in cpp similar to "<<":

mystream <<< param2 param3;

Is this possible? Does it already exist? One remark: I remember having seen this:

out <<STDERR param

Wouldnt this already be a ternary operator?


Solution

  • To send C++ output to the stderr stream, use cerr << var1 << var2 or clog << 1 << 2.

    There is exactly one ternary operator in C++, ?:, and it cannot be overloaded.

    <<< is a binary operator in all languages where I've seen it. C++ does not have it; such a character sequence would be parsed as << < which is nonsense as neither can be used as a unary operator.

    Finally, the second and third "operands" there are separated only by whitespace. C++ has no grammar productions including expression expression; that would lead to serious ambiguities.


    The chaining behavior as in cerr << var1 << var2 is achieved by overloads of the form

    std::ostream & operator << ( std::ostream &, my_class const & );
    

    The ostream & return type allows the result of the first call cerr << var1 to be used as the left-hand operand to << var2.