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

后端 未结 9 1805
误落风尘
误落风尘 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:34

    If you actually don't need to use the instance a (i.e. you can make it static like @mathengineer 's answer) you can simply pass in a non-capture lambda. (which decay to function pointer)


    #include 
    
    class aClass
    {
    public:
       void aTest(int a, int b)
       {
          printf("%d + %d = %d", a, b, a + b);
       }
    };
    
    void function1(void (*function)(int, int))
    {
        function(1, 1);
    }
    
    int main()
    {
       //note: you don't need the `+`
       function1(+[](int a,int b){return aClass{}.aTest(a,b);}); 
    }
    

    Wandbox


    note: if aClass is costly to construct or has side effect, this may not be a good way.

提交回复
热议问题