gpt4 book ai didi

c++ - 将对象的函数传递给另一个类的另一个 std::function

转载 作者:行者123 更新时间:2023-11-30 01:44:35 24 4
gpt4 key购买 nike

将一个类的成员函数传递给另一个类的 std::function 的正确方法是什么?

例如,下面的Bar要存储Foo对象的一个​​函数。

class Foo {
public:
Foo(int x) : data(x) {}
bool isEven(int y) { return (data + y) & 0x01; }
int data;
};

class Bar {
public:
std::function<bool(int)> testFunction;
};


int main() {
Foo foo1(1);
Bar bar;
bar.testFunction = std::bind(&Foo::isEven, &foo1);
if (bar.testFunction(3)) {
std::cout << "is even" << std::endl;
}
return 0;
}

这不编译:

no match for 'operator=' (operand types are 'std::function<bool(int)>' and 'std::_Bind_helper<false, bool (Foo::*)(int), Foo*>::type {aka std::_Bind<std::_Mem_fn<bool (Foo::*)(int)>(Foo*)>}')**

最佳答案

Foo::isEven 接受一个您稍后将传递的参数,因此您需要添加一个占位符来指示未绑定(bind)的参数。

bar.testFunction = std::bind(&Foo::isEven, &foo1, std::placeholders::_1);

或者只使用 lambda 而不是 bind

bar.testFunction = [&foo1](int x) { return foo1.isEven(x); };

关于c++ - 将对象的函数传递给另一个类的另一个 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36048029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com