Thursday, November 21, 2013

Me, me, me

Me me me: it's always me. 

Overwriting operator() to return an object itself as reference does two things:
1. make a class as a functor, so you can do something like f().
2. Return a reference to itself, which is why I call it "me me me" .


Example: 

class Me
{
public:
    Me(int a):theA(a){}
    Me& operator()(int a){theA+=a; return *this;}
    friend ostream& operator<<(ostream& os, Me a)
    {
        os << "Value is " << a.theA << endl;
        return os; 
    }

private:
    int theA;
};

Test code: 
        Me me(4);
        cout << me(1000)(200)(30);

Result: 
Value is 1234


me(10) is the same as object me.
me(10)(20) is the same as object me too.
me(10)(20)(30) is the same as object me as well.

So it's always me, me, me...... Isn't it kind of entertaining yourself while doing
tasteless coding, is it?

No comments:

Post a Comment