C++: Array of member function pointers to different functions

前端 未结 2 2011
滥情空心
滥情空心 2020-12-16 03:47

I have a class A which contains member functions foo() and bar() which both return a pointer to class B. How can I declare an array containing the functions foo and bar as a

2条回答
  •  不思量自难忘°
    2020-12-16 04:42

    The member function pointer syntax is ReturnType (Class::*)(ParameterTypes...), so e.g.:

    typedef B* (A::*MemFuncPtr)(); // readability
    MemFuncPtr mfs[] = { &A::foo, &A::bar }; // declaring and initializing the array
    B* bptr1 = (pointerToA->*mfs[0])(); // call A::foo() through pointer to A
    B* bptr2 = (instanceOfA.*mfs[0])(); // call A::foo() through instance of A
    

    See e.g. this InformIT article for more details on pointers to members.

    You might also want to look into Boost.Bind and Boost.Function (or their TR1 equivalents) which allow you to opaquely bind the member-function-pointers to an instance:

    typedef boost::function BoundMemFunc;
    A instanceOfA;
    BoundMemFunc mfs[] = { 
        boost::bind(&A::foo, &instanceOfA), 
        boost::bind(&A::bar, &instanceOfA) 
    };
    B* bptr = mfs[0](); // call A::foo() on instanceOfA
    

    To use such an array as a member, note that you can't initialize arrays using the member initializer list. Thus you can either assign to it in the constructor body:

    A::A {
        mfs[0] = &A::foo;
    }
    

    ... or you use a type that can actually be initialized there like std::vector or boost::array:

    struct A {
        const std::vector mfs;
        // ...
    };
    
    namespace {
        std::vector init_mfs() {
            std::vector mfs;
            mfs.push_back(&A::foo);
            mfs.push_back(&A::bar);
            return mfs;
        }
    }
    
    A::A() : mfs(init_mfs()) {}
    

提交回复
热议问题