Ulterior
Ulterior

Reputation: 2892

overloading operator ()

I have this declaration

struct Z {
    void operator ()( int a ) {
        cout << "operator()() " << a << endl;
    }
};

Z oz, *zp = &oz;

oz(1); //ok
(*zp)(2); //ok
zp(3); //"error: 'zp' cannot be used as a function"

Is there a way to modify struct declaration, so a call to No. 3 would succeed?

Upvotes: 1

Views: 978

Answers (2)

bitmask
bitmask

Reputation: 34628

Provided your Z type has no state you can change it into a function.

typedef void Y(int);
void y( int a ) {
  cout << "y() " << a << endl;
}

Y& oy = y;
Y* yp = &oy;

Now both oy(1) and yp(1) are legal, because function pointers are implicitly dereferenced when called.

Upvotes: 0

Etienne de Martel
Etienne de Martel

Reputation: 36852

That's expected behavior. zp is a pointer (a Z *), and operator() is overloaded for Z, not Z *. When you deference the pointer with *zp, you get a Z &, for which operator() is overloaded.

Unfortunately, you can't overload an operator for a pointer type (I think it has something to do with the fact that pointers are not user-defined types, but I don't have the Standard in front of me). You could simplify the syntax with references:

Z & r = *zp;
r(3);

Upvotes: 5

Related Questions