2

Help me understand the following code snippet:

(foo.h)

class Foo
{
   public:
        typedef void (MyType::*Handler)(SomeOtherType* t);

        Foo(Handler handler) : handler_(handler) { }

   private:
        Handler handler_;
};

(mytype.h)

class MyType
{
     public:
          MyType() { }
          void fun1() { }
          void fun2() { }    
};

What exactly is the typedef in foo.h declaring here? I can see that it's a function pointer of some kind but what's the significance of the asterisk? It appears to be de-referencing a type (??) and somehow trying to "attach" the newly typedef'd pointer to the type of MyType (?!?).

Can someone shed some light here please? Really confused :S

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
Daniel
  • 23,365
  • 10
  • 36
  • 34

2 Answers2

6

void (MyType::*)(SomeOtherType* t) is a pointer to a member function in class MyType that takes one argument (pointer to SomeOtherType) and returns nothing.

FAQ Lite entry.

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • Wowsers. I had no idea such a thing existed. Worse, the syntax is completely obtuse. These are just personal gripes though. Thank you very much! – Daniel Dec 01 '11 at 15:15
  • @Daniel: Good news is you don't have to use that crappy syntax. Look into `std::function` and `std::bind` (or `boost::function`/`boost::bind` if you're still on C++03). – Cat Plus Plus Dec 01 '11 at 15:18
  • 1
    @CatPlusPlus You might also mention that `::*` is a single token, not a concatenation of `::` and `*`. The wording in the original question makes me think that the poster isn't aware of this. – James Kanze Dec 01 '11 at 15:21
  • (removed previous comment; FAQ Lite already answers it). Thank you again! – Daniel Dec 01 '11 at 15:31
1

Pointer to a MyType member function returning void and taking pointer to SomeOtherType as a parameter.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173