Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使用函数绑定到成员函数?_C++_C++11 - Fatal编程技术网

C++ 如何使用函数绑定到成员函数?

C++ 如何使用函数绑定到成员函数?,c++,c++11,C++,C++11,如何使用somePointer; 设置为成员函数? 我在里面 class Temp { public: void test(string message) {} }; 我尝试了一些指针=&Temp::test; 但我犯了个错误。如何将某个指针绑定到某个类的成员函数?不能将该函数签名函数绑定到该成员函数。因为该成员函数需要Temp类的实例才能调用它。如果您有一个特定的临时实例要绑定,您可以这样做。例如,使用lambda Temp x; function<void(string)> s

如何使用somePointer; 设置为成员函数? 我在里面

class Temp {
public:
void test(string message) {}
};
我尝试了一些指针=&Temp::test;
但我犯了个错误。如何将某个指针绑定到某个类的成员函数?

不能将该函数签名函数绑定到该成员函数。因为该成员函数需要Temp类的实例才能调用它。如果您有一个特定的临时实例要绑定,您可以这样做。例如,使用lambda

Temp x;
function<void(string)> somePointer = [&x](string message) {
    x.test(message);
};

您也可以使用std::bind,但我会弄乱语法,因为我很少看到在lambdas存在的情况下使用它的任何理由。

您无法将该函数签名函数绑定到该成员函数。因为该成员函数需要Temp类的实例才能调用它。如果您有一个特定的临时实例要绑定,您可以这样做。例如,使用lambda

Temp x;
function<void(string)> somePointer = [&x](string message) {
    x.test(message);
};
您也可以使用std::bind,但我会弄乱语法,因为我很少看到在lambdas中使用它的任何理由。

使用:

您也可以使用lambda:

std::function<void(std::string message)> somePointer = 
    [&instance_of_temp](std::string message){instance_of_temp.test(message);}
使用:

您也可以使用lambda:

std::function<void(std::string message)> somePointer = 
    [&instance_of_temp](std::string message){instance_of_temp.test(message);}

尝试类似std::function f=std::bind&Temp::test、Temp{}、std::placeholder::_1;尝试类似std::function f=std::bind&Temp::test、Temp{}、std::placeholder::_1;消息参数仍然需要std::占位符::1。@remyabel已修复。谢谢消息参数仍然需要std::占位符::1。@remyabel已修复。谢谢