Calling C++ class methods via a function pointer

前端 未结 10 930
醉酒成梦
醉酒成梦 2020-11-22 06:47

How do I obtain a function pointer for a class member function, and later call that member function with a specific object? I’d like to write:

class Dog : A         


        
10条回答
  •  误落风尘
    2020-11-22 07:26

    I came here to learn how to create a function pointer (not a method pointer) from a method but none of the answers here provide a solution. Here is what I came up with:

    template  struct MethodHelper;
    template  struct MethodHelper {
        using T = Ret (C::*)(Args...);
        template  static Ret call(C* object, Args... args) {
            return (object->*m)(args...);
        }
    };
    
    #define METHOD_FP(m) MethodHelper::call
    

    So for your example you would now do:

    Dog dog;
    using BarkFunction = void (*)(Dog*);
    BarkFunction bark = METHOD_FP(&Dog::bark);
    (*bark)(&dog); // or simply bark(&dog)
    

    Edit:
    Using C++17, there is an even better solution:

    template  struct MethodHelper;
    template  struct MethodHelper {
        static Ret call(C* object, Args... args) {
            return (object->*m)(args...);
        }
    };
    

    which can be used directly without the macro:

    Dog dog;
    using BarkFunction = void (*)(Dog*);
    BarkFunction bark = MethodHelper<&Dog::bark>::call;
    (*bark)(&dog); // or simply bark(&dog)
    

    For methods with modifiers like const you might need some more specializations like:

    template  struct MethodHelper {
        static Ret call(const C* object, Args... args) {
            return (object->*m)(args...);
        }
    };
    

提交回复
热议问题