C++ std::tr1::bind使用


1. 简述

  同function函数相似。bind函数相同也能够实现相似于函数指针的功能。但却却比函数指针更加灵活。特别是函数指向类 的非静态成员函数时。std::tr1::function 能够对静态成员函数进行绑定,但假设要对非静态成员函数的绑定,需用到下机将要介绍的bind()模板函数。
  bind的声明例如以下:
  

template<class Fty, class T1, class T2, ..., class TN>
   unspecified bind(Fty fn, T1 t1, T2 t2, ..., TN tN);

  当中Fty为调用函数所属的类。fn为将被调用的函数,t1…tN为函数的參数。假设不指明參数,则能够使用占位符表示形參,占位符格式为std::tr1::placehoders::_1, std::tr1::placehoders::_2, …


2. 代码演示样例

  先看一下演示样例代码:
 

#include <stdio.h>
#include <iostream>
#include <tr1/functional>

typedef std::tr1::function<void()> Fun;
typedef std::tr1::function<void(int)> Fun2;

int CalSum(int a, int b){
    printf("%d + %d = %d\n",a,b,a+b);

    return a+b;
}

class Animal{
public:
    Animal(){}
    ~Animal(){}

    void Move(){}
};

class Bird: public Animal{
public:
    Bird(){}
    ~Bird(){}

    void Move(){
        std::cout<<"I am flying...\n";
    }
};

class Fish: public Animal{
public:
    Fish(){}
    ~Fish(){}

    void Move(){
        std::cout<<"I am swimming...\n";
    }

    void Say(int hour){
        std::cout<<"I have swimmed "<<hour<<" hours.\n";
    }
};

int main()
{
    std::tr1::bind(&CalSum,3,4)();

    std::cout<<"--------------divid line-----------\n";

    Bird bird;
    Fun fun = std::tr1::bind(&Bird::Move,&bird);
    fun();

    Fish fish;
    fun = std::tr1::bind(&Fish::Move,&fish);
    fun();

    std::cout<<"-------------divid line-----------\n";
    //bind style one.
    fun = std::tr1::bind(&Fish::Say,&fish,3);
    fun();

    //bind style two.
    Fun2 fun2 = std::tr1::bind(&Fish::Say,&fish, std::tr1::placeholders::_1);
    fun2(3);

    return 0;
}

  
  对于全局函数的绑定。可直接使用函数的地址,加上參数接口。std::tr1::bind(&CalSum,3,4)();。然后能够结合function函数。实现不同类成员之间的函数绑定。绑定的方式主要有代码中的两种。
  执行结果例如以下:
  

3 + 4 = 7
————–divid line———–
I am flying…
I am swimming…
————-divid line———–
I have swimmed 3 hours.
I have swimmed 3 hours.


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM