1

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?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Ulterior
  • 2,786
  • 3
  • 30
  • 58
  • I do not think this is possible, I am fairly sure you cannot overload pointers to your type. You could however write a wrapper class around your pointers that does allow this syntax. –  Dec 22 '11 at 04:36
  • 1
    If some thought was put into it, I'm sure some guru could come up with a way using the preprocessor to achieve your goal. But I sure hope that person wouldn't waste their time, since what you ask for is completely useless, and of no benefit to anyone, including you. – Benjamin Lindley Dec 22 '11 at 04:37
  • @benjamin-lindley you are right, that was a point... – Ulterior Dec 22 '11 at 04:43
  • Not that exact syntax, but you could add things so that `zp->call(3)` and/or `call(zp, 3)` work. – aschepler Dec 22 '11 at 04:46
  • Note that you overloaded `operator()` not `operator()()`. – Donotalo Dec 22 '11 at 04:52

2 Answers2

5

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);
Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
0

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.

bitmask
  • 32,434
  • 14
  • 99
  • 159