码迷,mamicode.com
首页 > 编程语言 > 详细

c++11: bind用法

时间:2014-10-11 18:40:25      阅读:387      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   sp   div   

原型:

templateclass R, class F, class... Args 

bind( F&& f, Args&&... args );

bind函数模板的作用是:

The function template bind generates a forwarding call wrapper for f. Calling this wrapper is equivalent to invoking with some of its arguments bound to args.

不怎么好翻译,尝试解释一下:我们为某个函数做一个bind,然后调用该bind和调用函数是一样的,跟函数指针有点像。

#include <random>
#include <iostream>
#include <memory>
#include <functional>
 
void f(int n1, int n2, int n3, const int& n4, int n5)
{
    std::cout << n1 <<   << n2 <<   << n3 <<   << n4 <<   << n5 << \n;
}
 
int g(int n1)
{
    return n1;
}
 
struct Foo {
    void print_sum(int n1, int n2)
    {
        std::cout << n1+n2 << \n;
    }
    int data = 10;
};
 
int main()
{
    using namespace std::placeholders;  // for _1, _2, _3...
 
    // demonstrates argument reordering and pass-by-reference
    int n = 7;
    // (_1 and _2 are from std::placeholders, and represent future
    // arguments that will be passed to f1)
    auto f1 = std::bind(f, _2, _1, 42, std::cref(n), n);
    n = 10;
    f1(1, 2, 1001); // 1 is bound by _1, 2 is bound by _2, 1001 is unused
 
    // nested bind subexpressions share the placeholders
    auto f2 = std::bind(f, _3, std::bind(g, _3), _3, 4, 5);
    f2(10, 11, 12);
 
    // bind to a member function
    Foo foo;
    auto f3 = std::bind(&Foo::print_sum, &foo, 95, _1);
    f3(5);
 
    // bind to member data
    auto f4 = std::bind(&Foo::data, _1);
    std::cout << f4(foo) << \n;

 

c++11: bind用法

标签:style   blog   color   io   os   ar   for   sp   div   

原文地址:http://www.cnblogs.com/457220157-FTD/p/4019034.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!