您的位置:首页 > 编程语言 > C语言/C++

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

2014-04-24 13:27 218 查看
std::bind 接受一个可调用的对象,一般就是函数呗。。

还是先上代码:

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


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

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又大显身手了:

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


短了好多好多啊。。。

这时候我们调用:

test_bind();


就会打印“hello!789”了。

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

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


这时候我们可以调用:

test_bind(1, 2);


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

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

在我看来,std::bind这个东西用在写事件回调中很好用~~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: