I'm trying to learn C++ and I'm experimenting with the std::bind function of the standard library. As a result, I understood that std::bind allows to wrap a function and to partially apply the function. This works very well with functions that are not member functions of a class. Now I try to use std::bind with class member functions and the 'this' pointer but I can't compile and don't know how to fix this problem. Could someone help me to really understand std::bind?
#include <iostream>
#include <functional>
class Class1 {
public:
Class1() = default;
~Class1() = default;
void print(std::function<void(void)> function2) {
function2();
};
};
class Class2 {
public:
Class2() = default;
~Class2() = default;
void test_bind() {
std::function<void(void)> function2 = std::bind<void(void)>(&Class2::print, this);
class1.print(function2);
}
void print() {
std::cout << "CLASS 2" << std::endl;
};
Class1 class1;
};
int main(int ac, char **av)
{
Class2 class2;
class2.test_bind();
}
Let the compiler deduce types based on passed arguments:
std::function<void(void)> function2 = std::bind(&Class2::print, this);
above is enough.
Version with explicit template arguments list looks like:
std::function<void(void)> function3 = std::bind<void(Class2::*)(),Class2*>(&Class2::print, this);
// std::bind<void(Class2::*)(),Class2*>
/ \ / \
| |---- pointer to type of object instance you invoke member function
|--- pointer to member function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.