C++ std::function 到成员函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5154116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:32:11  来源:igfitidea点击:

std::function to member function

c++function-pointers

提问by hidayat

#include <functional>

struct A
{
    int func(int x, int y)
    {
        return x+y;
    }
};

int main()
{

    typedef std::function<int(int, int) > Funcp;
    A a;
    //Funcp func = std:::bind(&A::func, &a);
    Funcp func = std::bind(&A::func, a, std::placeholders::_1);


    return 0;
}

I am getting errors in both of the above bind functions:

我在上述两个绑定函数中都遇到错误:

 error C2825: '_Fty': must be a class or namespace when followed by '::'

Where is the syntax error? I am using visual studio 2010

语法错误在哪里?我正在使用 Visual Studio 2010

回答by ltjax

Funcp func = std::bind(&A::func, &a, std::placeholders::_1, std::placeholders::_2);

Funcp func = std::bind(&A::func, &a, std::placeholders::_1, std::placeholders::_2);

回答by ap-osd

It took a while for me to figure out what's happening. So adding it here for the benefit of others, where an explanation would help. I've renamed some functions and variables for more clarity.

我花了一段时间才弄清楚发生了什么。因此,为了其他人的利益,将其添加到此处,解释会有所帮助。为了更清晰,我重命名了一些函数和变量。

#include <functional>

struct A
{
    int MemberFunc(int x, int y) 
    {
        return x+y;
    }
};

int main()
{
    typedef std::function<int(int, int) > OrdinaryFunc;

    A a;
    OrdinaryFunc ofunc = std::bind(&A::MemberFunc, a, std::placeholders::_1, std::placeholders::_2);

    int z = ofunc(10, 20); // Invoke like an ordinary function

    return 0;
}

Class member functions have an implicit/hidden parameter which points to the object (thispointer). These member functions can be invoked only by providing an object, which makes it different from an ordinary function.

类成员函数具有指向对象(this指针)的隐式/隐藏参数。这些成员函数只能通过提供一个对象来调用,这使得它不同于普通函数。

std::bindcan be used to "convert" a member function into an ordinary function. In the new function, the object is boundto the implicit/hidden parameter of the member function, and need not be passed when invoked. The unbound arguments are represented by the placeholders _1, _2and have to be passed when invoked.

std::bind可用于将成员函数“转换”为普通函数。在新函数中,对象绑定到成员函数的隐式/隐藏参数,调用时不需要传递。未绑定的参数由占位符表示_1_2并且必须在调用时传递。