C ++ syntax for a member function that returns a pointer to a function

I have the following program that I would like to fix. Not sure how to make it syntactically correct.

class A{
    void f(){};
    void (A::*)()get_f(){return &A::f;}
};

In addition, I would like to end up moving the function definition circuit as shown below.

void A::(*)()A::get_f(){
    return &A::f;
}

What is the correct syntax here too?

Many thanks for your help!

+5
source share
5 answers

Like this:

class A{
    void f(){};
    void (A::*get_f())() {return &A::f;}
};

and similarly:

void (A::* A::get_f())(){
    return &A::f;
}

Watch in action on ideone . Note that using this parameter is exactly the same as with typedef (in other answers).

BTW, for extra points and vomiting (ha, ha):

void (A::* (A::* get_get_f())())();
+5
source

Just use typedef:

class A {
    typedef void (A::*AFn)();

    void f() { }

    AFn get_f(){ return &A::f; }
};
+1
source

typedef:

class A
{
  typedef void (A::*funptr)();
  void f() {}
  funptr get_f() { return &A::f; }
};

,

class A
{
  void f() {}
  void (A::*get_f())() { return &A::f; }
};
+1

Using typedef, it just makes syntax easy.

In the following example, a function is defined outside of your class.

class A{
    typedef void (A::*p)();
    void f(){};
    p get_f();
};

A::p A::get_f() { return &A::f; }

You can define it inside a class in the same way

class A{
    typedef void (A::*p)();
    void f(){};
    p get_f() { return &A::f; }
};
+1
source
class A{
public:
    typedef void(A::*mem_ptr)();
    void f(){};
    mem_ptr get_f();
};

A::mem_ptr A::get_f()
{return &A::f;}

int main() {
    A a;
    A::mem_ptr p = a.get_f();
    (a.*p)();
}

http://ideone.com/Q7G4s

Source: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.6

0
source

All Articles