C++std::tr 1::bind使用
1.簡単に述べる
function関数と同様にbind関数も関数ポインタと同様の機能を実現できるが,関数ポインタよりも柔軟であり,特に関数がクラスの非静的メンバー関数を指す場合である.std::tr 1::functionは静的メンバー関数をバインドできますが、非静的メンバー関数をバインドする場合は、説明するbind()テンプレート関数を下機で使用する必要があります.bindの声明は以下の通りです.
ここで、Ftyは呼び出し関数が属するクラスであり、fnは呼び出される関数であり、t 1…tNは関数のパラメータである.パラメータを指定しない場合は、std::tr 1::placehoders::1, std::tr1::placehoders::_2, …
2.コード例
サンプルコードを見てみましょう.
グローバル関数のバインドでは、関数のアドレスを直接使用し、パラメータインタフェースを追加できます.
3 + 4 = 7 ————–divid line———– I am flying… I am swimming… ————-divid line———– I have swimmed 3 hours. I have swimmed 3 hours.
function関数と同様にbind関数も関数ポインタと同様の機能を実現できるが,関数ポインタよりも柔軟であり,特に関数がクラスの非静的メンバー関数を指す場合である.std::tr 1::functionは静的メンバー関数をバインドできますが、非静的メンバー関数をバインドする場合は、説明するbind()テンプレート関数を下機で使用する必要があります.bindの声明は以下の通りです.
template<class Fty, class T1, class T2, ..., class TN>
unspecified bind(Fty fn, T1 t1, T2 t2, ..., TN tN);
ここで、Ftyは呼び出し関数が属するクラスであり、fnは呼び出される関数であり、t 1…tNは関数のパラメータである.パラメータを指定しない場合は、std::tr 1::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
",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...
";
}
};
class Fish: public Animal{
public:
Fish(){}
~Fish(){}
void Move(){
std::cout<<"I am swimming...
";
}
void Say(int hour){
std::cout<<"I have swimmed "<<hour<<" hours.
";
}
};
int main()
{
std::tr1::bind(&CalSum,3,4)();
std::cout<<"--------------divid line-----------
";
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-----------
";
//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関数と組み合わせて、異なるクラスのメンバー間の関数バインドを実現できます.バインドの方法は主にコードの2つがあります.実行結果は次のとおりです.3 + 4 = 7 ————–divid line———– I am flying… I am swimming… ————-divid line———– I have swimmed 3 hours. I have swimmed 3 hours.