C++ C++;指向类成员的函数指针 不存在从“std::_Binder”到“std::function”的合适的用户定义转换

C++ C++;指向类成员的函数指针 不存在从“std::_Binder”到“std::function”的合适的用户定义转换,c++,function,std,bind,C++,Function,Std,Bind,所以。。。我真的不知道我的错误在哪里。从去年夏天开始,我就没有使用函数指针,但我知道这个例子在我学习std::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)>" exist

所以。。。我真的不知道我的错误在哪里。从去年夏天开始,我就没有使用函数指针,但我知道这个例子在我学习std::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
#包括
#包括
#包括
课堂测试
{
公众:
无效显示(int p_测试)
{

std::cout您必须像这样使用std::函数

#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::函数
正如@user0042所建议的,
auto
将在这里完成这项工作,但我认为您希望存储一个functor。那么
std::function
就是正确的方法。
auto
如果你想在类或类似的东西中存储一个函子,那是没有用的。
std::bind
确实有点神秘,但我认为没有必要用
lambda
来解决这个问题。

你必须像这样使用std::函数

#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::函数
正如@user0042所建议的,
auto
将在这里完成这项工作,但我认为您希望存储一个functor。那么
std::function
就是正确的方法。
auto
如果你想在类或类似的东西中存储一个函子,那就没用了。
std::bind
确实有点神秘,但我认为不需要
lambda
来解决这个问题。

如果你真的想绑定
display
函数的两个参数(即隐式
this
参数和显式
int
参数),则您的
display
成员函数在绑定后变为
void()
函数

std::function<void()>
如果您不想绑定任何参数,那么您的
display
函数是一个具有
Test*
int
类型两个参数的函数

std::function<void (int)> test = std::bind(&Test::display, &t1, std::placeholders::_1);
test(42);
std::function test=&test::display;
测试(&t1,123);

因此,您需要首先确定要绑定哪些参数以及要保持未绑定状态的参数。

如果您确实要绑定
display
函数的两个参数(即隐式
参数和显式
int
参数),则您的
display
成员函数在绑定后变为
void()
函数

std::function<void()>
如果您不想绑定任何参数,那么您的
display
函数是一个具有
Test*
int
类型两个参数的函数

std::function<void (int)> test = std::bind(&Test::display, &t1, std::placeholders::_1);
test(42);
std::function test=&test::display;
测试(&t1,123);

因此,您需要首先确定要绑定哪些参数以及要保持未绑定状态的参数。

使用
auto
和lambda函数代替
std::bind()
。使用
auto
和lambda函数代替
std::bind())
。不是我的否决票。但是如果你使用OP的
bind
调用,那么你需要
std::function
,而不是
std::function
。OP的
bind
绑定两个参数。不是我的否决票。但是如果你使用OP的
bind
调用,那么你需要的是
std::function
,而不是
std::function
。OP的
bind
绑定两个参数。