指向 class 成员的 C++ 函数指针
C++ function pointer to class member
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);
}
你必须像这样使用std::function。
std::function<void()>
正如@user0042 所建议的那样,auto
可以完成这里的工作,但我认为您想 store 一个仿函数。那么 std::function
是正确的方法。
auto
将无济于事,如果您想将仿函数存储在 class 或类似的东西中。 std::bind
确实有点神秘,但我认为不需要 lambda
来解决这个问题。
如果您真的想绑定 display
函数的两个参数(即隐式 this
参数和显式 int
参数),那么您的 display
绑定
后成员函数变成了void ()
函数
std::function<void ()> test = std::bind(&Test::display, &t1, 1);
test();
如果您只绑定 this
参数,那么它将成为一个 void (int)
函数
std::function<void (int)> test = std::bind(&Test::display, &t1, std::placeholders::_1);
test(42);
如果你不想绑定任何参数,那么你的display
函数就是一个Test *
和int
类型两个参数的函数
std::function<void (Test *, int)> test = &Test::display;
test(&t1, 123);
所以,你需要先决定哪些参数你想绑定,哪些参数你想保持不绑定。
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);
}
你必须像这样使用std::function。
std::function<void()>
正如@user0042 所建议的那样,auto
可以完成这里的工作,但我认为您想 store 一个仿函数。那么 std::function
是正确的方法。
auto
将无济于事,如果您想将仿函数存储在 class 或类似的东西中。 std::bind
确实有点神秘,但我认为不需要 lambda
来解决这个问题。
如果您真的想绑定 display
函数的两个参数(即隐式 this
参数和显式 int
参数),那么您的 display
绑定
void ()
函数
std::function<void ()> test = std::bind(&Test::display, &t1, 1);
test();
如果您只绑定 this
参数,那么它将成为一个 void (int)
函数
std::function<void (int)> test = std::bind(&Test::display, &t1, std::placeholders::_1);
test(42);
如果你不想绑定任何参数,那么你的display
函数就是一个Test *
和int
类型两个参数的函数
std::function<void (Test *, int)> test = &Test::display;
test(&t1, 123);
所以,你需要先决定哪些参数你想绑定,哪些参数你想保持不绑定。