简体   繁体   中英

Function pointer inside class point to that class's member function

I am familiar with the function pointer to class member issue, which requires the signature to be ClassName::*FuncPtr , but I have this nuanced problem where I need the function pointer to be to a containing class member:

class F
{
public:
    class Container;
    typedef void (Container::*FuncPtr)();
    
    F(FuncPtr fp) : m_fp(fp) {}
    void Execute() { (*this.*m_fp)(); }
private:
    FuncPtr m_fp;
};

class Container
{
public:
    Container() : fps(&Container::Func) { }
    void Func() { }
private:
    F fps;
};

So, basically I want to create an object Container , which will send in its constructor a pointer to one of its member functions to the F object it contains, which should store that function pointer.

You need to move the forward declaration class Container; outside of F . Inside of F , it is declaring F::Container , which is a different type than Container .

Also, (*this.*m_fp)() (alternatively (this->*m_fp)() ) won't work at all, as m_fp is expecting a Container object on the left side of .* (or ->* ), but this is pointing at an F object instead. So Container will have to pass its this pointer to F 's constructor to be stored along with m_fp .

Try this:

#include <iostream>
using namespace std;

class Container;

class F
{
public:
    typedef void (Container::*FuncPtr)();
    
    F(Container &c, FuncPtr fp) : m_c(c), m_fp(fp) {}
    void Execute() { (m_c.*m_fp)(); }
private:
    Container& m_c;
    FuncPtr m_fp;
};

class Container
{
public:
    Container() : fps(*this, &Container::Func) { }
    void Func() { ... }
private:
    F fps;
};

Online Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM