dimanche 14 juillet 2019

How to pass lamda as a function pointer argument of member function?

I learned how to pass member functions to another member function as a function pointer argument.

Now, I'm trying to pass lamda as a function pointer argument of member function.

My Code:

#include <iostream>

using namespace std;

class Test
{
public:
    int add(int a, int b)
    {
        return a + b;
    }
    int sub(int a, int b)
    {
        return a - b;
    }
    typedef int (Test::*funcPtr)(int a, int b);
    int myFunc(funcPtr func, int a, int b)
    {
        return (this->*func)(a, b);
    }
    void setup()
    {
        cout << myFunc(&Test::add, 5, 3) << endl;
        cout << myFunc(&Test::sub, 5, 3) << endl;
        cout << myFunc([](int a, int b) {return a * b;}, 5, 3) << endl; //ERROR!!!
    }
};

int main()
{
    Test test;
    test.setup();
}

Result:

Error: : No viable conversion from lambda to 'Test::funcPtr' (aka 'int (Test::*)(int, int)')

Expected Result:

8
2
15

How should I correct my code so I can get the expected result?

Aucun commentaire:

Enregistrer un commentaire