no suitable user-defined conversion from "std::_Binder<std::_Unforced, void (Test::*)(int p_test), Test *, int>" to "std::function<void (Test::*)(int)>" exists
所以...我真的不知道我的错误在哪里。我从去年夏天开始就没有使用过函数指针,但我知道这个例子曾经在我学习 std::function 和 std::bind 时起作用。
#include <iostream>
#include <string>
#include <functional>
class Test
{
public:
void display(int p_test)
{
std::cout << p_test;
}
};
void main()
{
Test t1;
std::function<void(Test::*)(int)> test = std::bind(&Test::display, &t1, 1);
}
最佳答案
如果您真的想绑定(bind)display
函数的两个参数(即隐式this
参数和显式int
参数),那么你的display
成员函数绑定(bind)后就变成了void()
函数
std::function<void ()> test = std::bind(&Test::display, &t1, 1);
test();
如果你只绑定(bind)this
参数,那么它将变成一个void (int)
函数
std::function<void (int)> test = std::bind(&Test::display, &t1, std::placeholders::_1);
test(42);
如果你不想绑定(bind)任何参数,那么你的display
函数就是一个带有Test *
和int
两个参数的函数类型
std::function<void (Test *, int)> test = &Test::display;
test(&t1, 123);
因此,您需要先确定要绑定(bind)哪些参数以及不绑定(bind)哪些参数。
关于指向类成员的 C++ 函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47946312/