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

时间:2017-12-22 19:14:33

标签: 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);
}

2 个答案:

答案 0 :(得分:3)

如果您确实要绑定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 *函数是一个包含intstd::function<void (Test *, int)> test = &Test::display; test(&t1, 123); 类型

两个参数的函数
Any

因此,您需要先确定要绑定的参数以及要保持未绑定的参数。

答案 1 :(得分:-1)

你必须像这样使用std :: function。

std::function<void()>

正如@ user0042建议的那样,auto会在这里完成工作,但我认为你想存储一个仿函数。然后std::function是正确的方法。 如果你想在类或类似的东西中存储一个仿函数,auto将无济于事。 std::bind确实有点神秘,但我不认为lambda是解决这个问题的必要条件。

相关问题