C++ - is it possible to extract class and argument types from a member function type in a template?

前端 未结 4 1688
孤独总比滥情好
孤独总比滥情好 2021-02-15 18:19

I would like to wrap member functions that conform to the type \'void (ClassType::Function)(ArgType)\' with a templated class. Later, I want to pass an instance of ClassType to

4条回答
  •  臣服心动
    2021-02-15 18:40

    In C++11 you might use lambdas, like:

    template 
    std::function wrapper(void (X::*mfp)(ARG))
    {
        return [=](X *x, ARG arg) {
           (x->*mfp)(arg);
        };
    }
    

    With VisualC++ (at least as recent as VS2013), use capture by value [=] when capturing member function pointers (or experience crashes).

    Playground:

    #include 
    #include 
    
    struct A {
        virtual void a(int i) { std::cout << "A: " << i << std::endl; }
    };
    
    struct B {
        virtual void b(int i) { std::cout << "B: " << i << std::endl; }
    };
    
    template 
    std::function wrapper(void (X::*mfp)(ARG)) {
        return [=](X *x, ARG arg) { (x->*mfp)(arg); };
    }
    
    int main()
    {
        auto g = wrapper(&B::b);
        B b;
        g(&b, 3);
        auto h = wrapper(&A::a);
        A a;
        h(&a, 4);
        return 0;
    }
    

提交回复
热议问题