同function函數類似。bind函數相同也可以實現類似於函數指針的功能。但卻卻比函數指針更加靈活。特別是函數指向類 的非靜態成員函數時。std::tr1::function 可以對靜態成員函數進行綁定,但假設要對非靜態成員函數的綁定,需用到下機將要介紹的bind()模板函數。
bind的聲明例如如下:
ios
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, …markdown
先看一下演示樣例代碼:
函數
#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函數。實現不一樣類成員之間的函數綁定。綁定的方式主要有代碼中的兩種。
執行結果例如如下:
post
3 + 4 = 7
————–divid line———–
I am flying…
I am swimming…
————-divid line———–
I have swimmed 3 hours.
I have swimmed 3 hours.ui