C++ passing method pointer as template argument

前端 未结 5 945
攒了一身酷
攒了一身酷 2021-01-19 23:44

I have a caller function like this:

template
void CallMethod(T *object){
    (object->*method)(args);
}
         


        
5条回答
  •  后悔当初
    2021-01-20 00:24

    What if 2 methods have the exact same signature ?

    The template can not distinguish on it (it selects on type, not value) and thus the same generated template function will call the first method or the second, would you bet your hand on it ?

    You can use some tricks to make a different type at compile time, using the __LINE__ macro, but it involves mixing macro with current code which will be hard to follow. This code:

    template
    void CallMethod(T *) { ... }
    #define MakeCallMethod(X, Y) &CallMethod
    
    // This will work (it does not without the __LINE__ trick, ptr1 == ptr2 in that case)
    typedef void (*ptrFunc)(A *);
    ptrFunc ptr1 = MakeCallMethod(A, method);
    ptrFunc ptr2 = MakeCallMethod(A, otherMethodWithSameSignature);
    
    Assert(ptr1 != ptr2);
    

    However you'll not be able to save the pointer to a method in a variable and make a "auto wrapper" from it. It's now runtime, you need a runtime solution for this.

提交回复
热议问题