繁体   English   中英

如何将lamda作为成员函数的函数指针参数传递?

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

我学习了如何将成员函数作为函数指针参数传递给另一个成员函数。

现在,我试图将lamda作为成员函数的函数指针参数传递。

我的代码:

#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();
}

结果:

错误::没有从lambda到'Test :: funcPtr'的可行转换(又名'int(Test :: *)(int,int)')

预期结果:

8
2
15

我应该如何纠正我的代码,以便获得预期的结果?

一种选择是使函数static ,然后将std::function用作类型:

using funcType = std::function<int(int, int)>;
int myFunc(funcType func, int a, int b)
{
    return 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;
}

生活

感谢@holyBlackCat ,另一个选择是使用常规函数指针(成员函数必须是static ):

typedef int (*funcPtr)(int a, int b);
//or:
//using funcPtr =  int (*)(int a, int b);
int myFunc(funcPtr func, int a, int b)
{
    return (*func)(a, b);
}

以及模板:

template<typename funcType>
int myFunc(funcType func, int a, int b)
{
    return 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;
}

常规函数指针live模板live


编辑

上面提供的示例仅适用于静态成员函数。 要调用非静态成员函数,可以使用指向成员函数类型的指针

using funcPtr = int(Test::*)(int a, int b);
int myFunc(funcPtr func, int a, int b)
{
    return invoke(func, this, a, b);
}

//..
// call:
cout << myFunc(&Test::add, 5, 3) << endl;

指向非静态成员函数现场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM