#include <iostream>
#include <string>
#include <vector>
#include <functional>
using namespace std;
void foo(const string &s)
{
cout << s << endl;
}
int main(int argc, const char *argv[])
{
void (*pFunc) (const string &) = &foo;
pFunc("bar");
function<void (const string&)> f = &foo;
f("bar");
return 0;
}
#include <iostream>
#include <string>
#include <vector>
#include <functional>
using namespace std;
void foo(int i, double d)
{
cout << i << d << endl;
}
int main(int argc, const char *argv[])
{
function<void (int, double)> f = &foo;
f(12, 4.5);
return 0;
}
#include <iostream>
#include <string>
#include <vector>
#include <functional>
using namespace std;
class Foo
{
public:
void foo(int i) { cout << i << endl; }
static void bar(double d) { cout << d << endl; }
};
int main(int argc, const char *argv[])
{
//mem_fun void (*)(Foo *, int)
Foo f;
(mem_fun(&Foo::foo))(&f, 123); //把成员函数转换成函数对象
function<void (int)> pf = bind(&Foo::foo,
&f,
std::placeholders::_1);
pf(345);
function<void (Foo*, int)> pf2 = bind(&Foo::foo,
std::placeholders::_1,
std::placeholders::_2);//数字代表原函数第几个参数
pf2(&f, 456);
function<void (int, Foo*)> pf3 = bind(&Foo::foo,
std::placeholders::_2,
std::placeholders::_1);
pf3(567, &f);
return 0;
}
#include <iostream>
#include <string>
#include <vector>
#include <functional>
using namespace std;
using namespace std::placeholders;
void test(int i, double d, const string &s)
{
cout << "i = " << i << " d = " << d << " s = " << s << endl;
}
int main(int argc, const char *argv[])
{
function<void (int, double, const string&)> f1 = &test;
f1(12, 3.14, "foo");
//1.void (*)(int, double)
function<void (int, double)> f2 =
std::bind(&test,
_1,
_2,
"foo");
//2.void (*)(double, int, const string &)
function<void (double, int, const string &)> f3 =
std::bind(&test,
_2,
_1,
_3);
//3.void (*)(const string &, int)
function<void (const string &, int)> f4 =
std::bind(&test,
_2,
3.4,
_1);
//4. void (*) (const string &, int, double)
function<void (const string&, int, double)> f5
= std::bind(&test,
_2,
_3,
_1);
//5. void (*)(int)
function<void (int)> f6 =
bind(&test,
_1,
3.4,
"bar");
//6 void(*)(const string &)
function<void (const string &)> f7 =
bind(&test,
12,
4.5,
_1);
//7. void (*)()
function<void()> f8 =
bind(&test,
12,
4.5,
"bar");
}