How can I pass a member function where a free function is expected?

后端 未结 9 1809
误落风尘
误落风尘 2020-11-22 15:10

The question is the following: consider this piece of code:

#include 


class aClass
{
public:
    void aTest(int a, int b)
    {
        prin         


        
9条回答
  •  忘掉有多难
    2020-11-22 15:27

    Not sure why this incredibly simple solution has been passed up:

    #include 
    
    class aClass
    {
    public:
        void aTest(int a, int b)
        {
            printf("%d + %d = %d\n", a, b, a + b);
        }
    };
    
    template
    void function1(void (C::*function)(int, int), C& c)
    {
        (c.*function)(1, 1);
    }
    void function1(void (*function)(int, int)) {
      function(1, 1);
    }
    
    void test(int a,int b)
    {
        printf("%d - %d = %d\n", a , b , a - b);
    }
    
    int main (int argc, const char* argv[])
    {
        aClass a;
    
        function1(&test);
        function1(&aClass::aTest, a);
        return 0;
    }
    

    Output:

    1 - 1 = 0
    1 + 1 = 2
    

提交回复
热议问题