Vector of pointer to member functions

房东的猫 提交于 2019-12-02 10:49:12
typedef void(*classFuncPtr)();

This is not a pointer to method, but a pointer to function. Method differs from function, because it's being called in a context: requires this to work correctly.

Keep in mind, that in C++ you are only able to create vector of pointers to a method of specific class. So you won't be able to keep pointers to two methods of different classes in that vector.

The solution - as suggested in comments - is to use std::function or boost::function and possibly C++11 lambdas, because they provide a lot more flexibility than simple pointer-to-members.

If you want to implement an event mechanism, consider also using functors instead of methods:

  1. Create base class for event handler:

    class MyEventHandler
    {
    public:
        virtual void operator()(void * sender, int data) = 0;
    }
    
  2. Create simple vector of these:

    std::vector<MyEventHandler *> MyEvent;
    
  3. Create specific handlers in your classes:

    class MyClass
    {
    private:
        class SpecificEventHandler : MyEventHandler
        {
        public:
            void operator()(void * sender, int data)
            {
                std::cout << "Event handled!";
            }
        }
    
    public:
        SpecificEventHandler Handler;
    
        MyClass()
        {
        }
    }
    
  4. Hook the handler to your event:

    MyEvent.push_back(&(myClassInstance.Handler));
    

Code written from memory, may not compile, but you should get the idea.

std::function< void() > 

looks like the signature you are looking for. If it isn't available in your version of C++ but you can use boost, then you fill find it in boost. Look up documentation for appropriate header, for std, for function.

To create one for a member function, you need to bind it, and to bind it to FunctionVectors::a() you will need an instance of a FunctionVectors to call it on.

In your example, I will make the typedef for you

typedef std::function< void() > classFuncPtr; // in reality a badly named typedef

int main() { FunctionVectors f; classFuncPtr fv = std::bind( &FunctionVectors::a, f ); }

alternatively if you really have C++11 with lambdas you can do

   classFuncPtr = [ f ]() { f.a() );

In your case I reckon you don't really want a free function, you always want a member function of your class you want.

   typedef void (*FunctionVectors::classFuncPtr )();

and you would use

    (this->*func)(); 

to invoke it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!