views:

274

answers:

1

Hi, I'm trying to overload the comma operator with a non-friend non-member function like this:

#include <iostream>
using std::cout;
using std::endl;

class comma_op
{
    int val;

public:
    void operator,(const float &rhs)
    {
        cout << this->val << ", " << rhs << endl;
    }
};

void operator,(const float &lhs, const comma_op &rhs)
{
    cout << "Reached!\n";      // this gets printed though
    rhs, lhs;                  // reversing this leads to a infinite recursion ;)
}

int main()
{
    comma_op obj;
    12.5f, obj;

    return 0;
}

Basically, I'm trying to get the comma operator usable from both sides, with a float. Having a member function only allows me to write obj, float_val, while having a additional helper non-friend non-member function allows me to write float_val, obj; but the member operator function doesn't get called.

GCC cries:

comma.cpp: In function ‘void operator,(const float&, const comma_op&)’:
comma.cpp:19: warning: left-hand operand of comma has no effect
comma.cpp:19: warning: right-hand operand of comma has no effect


Note: I realise that overloading operators, that too to overload comma op., is confusing and is not at all advisable from a purist's viewpoint. I'm just learning C++ nuances here.

+17  A: 
void operator,(const float &rhs)

You need a const here.

void operator,(const float &rhs) const {
    cout << this->val << ", " << rhs << endl;
}

The reason is because

rhs, lhs

will call

rhs.operator,(lhs)

Since rhs is a const comma_op&, the method must be a const method. But you only provide a non-const operator,, so the default definition will be used.

KennyTM
Oh const correct-ness! Yes, it works now, thanks :)
legends2k