C++ 11 笔记 (四) : std::bind

std::bind 接受一个可调用的对象,一般就是函数呗。。

还是先上代码:

1 void func(int x, int y, int z)
2 {
3     std::cout << "hello!" << x << y << z << std::endl;
4 }

我们可以通过std::bind调用这个函数:

1 std::_Bind<true, void, void(*const)(int, int, int), int, int, int> test_bind = std::bind(func, 7, 8, 9);

其中7,8,9是传给func函数的参数。看这恶心的声明,简直比上一篇博客举得例子还要恶心,所以auto又大显身手了:

1 auto test_bind = std::bind(func, 7, 8, 9);

短了好多好多啊。。。

 

这时候我们调用:

1 test_bind();

就会打印“hello!789”了。

 

然后再说一下占位符,我们把test_bind改成这样:

1 auto test_bind = std::bind(func, std::placeholders::_1, std::placeholders::_2, 9);

这时候我们可以调用:

1 test_bind(1, 2);

就会打印“hello!129”。也就是前两个参数是可以指定的了。(第三个参数不可以)。

其中 std::placeholders::_1 是占位符,我试了试好像能到 _20 (这。。)

 

在我看来,std::bind这个东西用在写事件回调中很好用~~~

posted @ 2014-04-24 13:27  Anti-Magic  阅读(235)  评论(0编辑  收藏  举报