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