0

The Goal

I would like an overloaded function that can handle having the struct on the right-hand side of the operator.

Overload "<<" operator to achieve;

std::cout << vec3 << std::endl;

Where I Am

Struct;

struct vec3
{
    float x;
    float y;
    float z;

    std::ostream& operator << (std::ostream &o)
    {
        return o << x << y << z;
    }
}

Attempts;

std::cout << vec3(0,0,0) << std::end;

Tells me that "No Operator Matches Operands"

vec3(0,0,0) << std::cout << std::endl;

Gives me the desired result, however this is not how I would prefer to layout code like this.

It may be the case I am misinterpreting the error messages but this is what I am gathering from it.


I am struggling to find any particularly concise resources for the syntax required to handle an operation where the struct is on the right-hand side of the operator. In the form:

OTHER_TYPE OPERATOR STRUCT

As apposed to:

STRUCT OPERATOR OTHER_TYPE
IsamuelB
  • 11
  • 1
  • 1
  • 3
    Have a free function: `std::ostream& operator<<(std::ostream&, vec3 const&)` and then friend it _if necessary_. – Mike Vine Feb 17 '22 at 14:21
  • 1
    As a member function, the object must be on the left-hand side of the operator, that's how it works. E.g. `vec3(0,0,0) << std::cout` will then be compiled as `vec3(0,0,0).operator<<(std::cout)`. To have the "object" on the right-hand side of the operator the overload must be as a *non* member function. And take the object as the second argument. To be honest, this should have been very clear in any decent [book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282), class or tutorial. – Some programmer dude Feb 17 '22 at 14:24
  • 1
    Generally speaking, an expression like `a op b` can be either `a.operator op(b)` or `operator op(a, b)`. – Some programmer dude Feb 17 '22 at 14:26
  • @Someprogrammerdude thanks a lot, it was non-member functions I was missing, It's all working now. – IsamuelB Feb 17 '22 at 14:34

0 Answers0