bind_test.cpp
#include <fmt/format.h>
#include <console_color.h>
#include <boost/bind.hpp>
using namespace std;
using namespace fmt;
using namespace concol;
using namespace boost;
int f(int a, int b) { return a + b; }
int g(int a, int b, int c) { return a + b * c; }
typedef int(*f_type)(int, int);
typedef int(*g_type)(int, int, int);
class Demo {
public:
int f(int a, int b) { return a + b; }
};
int main(int argc, char **argv)
{
init();
// common bind
cout << bind(f, 1, 2)() << endl;
auto g1 = bind(g, 1, 2, 3);
cout << g1() << endl;
print_cyan_line();
// postitional bind
cout << bind(f, _1, 9)(3) << endl; // 12
cout << bind(f, _1, _2)(4, 6) << endl; // 10
cout << bind(f, _1, _1)(9, 10) << endl; // 18
print_cyan_line();
// bind function pointer
f_type pf = f;
g_type pg = g;
cout << bind(pf, _1, 8)(7) << endl; // 15
cout << bind(pg, _3, _2, _1)(2, 3, 4) << endl; //10
print_cyan_line();
// bind member function by instance, reference and class pointer
Demo a, &ra = a;
Demo* p = &a;
cout << bind(&Demo::f, a, _1, 20)(10) << endl;
cout << bind(&Demo::f, ra, _1, 20)(11) << endl;
cout << bind(&Demo::f, p, _1, 20)(12) << endl;
print_cyan_line();
cout << "Press any key to exit..." << endl;
get_char();
return 0;
}
运行结果
