指向类成员的 C++ 函数指针

标签 c++ function std bind

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/

相关文章:

c++ - 有效地列出目录中的所有子目录

php - 函数与对象最佳实践

c++ - 字符串输入/输出

c++ - 鼠标指针渲染器

javascript - 对 JavaScript 的理解

python - 获取没有定义行的 Python 函数的源代码

c++ - 为什么 iostream 包含 time.h?

C++ EOF 命名空间

C++ STL 访问 vector 元素

c++ - libboost_date_time 链接器错误