Boost C++ Librariesプログラミング 第2版
![]() | Boost C++ Librariesプログラミング 第2版 稲葉 一浩 (2007/07) 秀和システム この商品の詳細を見る サポートページはこちら |
'準'標準ライブラリともいえるboostの解説書です。
第2版では、Version 1.34に対応しており、Version 1.35の一部も先取りされています。boost使いは是非、手元に置いておきたい一冊です。
std::tr1::bind
Problem
std::tr1::bindとはいったい何なのでしょうか?
Solution
std::tr1::mem_fnのWidgetクラスのメンバ関数test()がint型の引数を一つ要求したとします。
このような場合、std::mem_funやstd::tr1::mem_fnに加えstd::bind1stやstd::bind2ndが必要になります。
に変更した場合、どうなるでしょうか?
答えはコンパイルエラーです。
最後に、メンバ関数test()に第2引数が追加された場合、どうなるでしょうか?
答えはstd::tr1::bindに引数を追加するだけです。
std::tr1::bindとはいったい何なのでしょうか?
Solution
std::tr1::mem_fnのWidgetクラスのメンバ関数test()がint型の引数を一つ要求したとします。
class Widget {
public:
...
void test(int n); // 自己テストを実行する。
...
};
list<Widget*> lpw;
コンテナのすべてのWidgetをテストするために、再びstd::for_eachを使用します。このような場合、std::mem_funやstd::tr1::mem_fnに加えstd::bind1stやstd::bind2ndが必要になります。
#include <list>
#include <algorithm>
#include <functional>
#include <tr1/functional>
class Widget {
public:
void test(int n) {}
};
int main()
{
std::list<Widget*> lspw;
std::for_each(lspw.begin(), lspw.end(), std::bind2nd(std::mem_fun(&Widget::test), 0));
std::for_each(lspw.begin(), lspw.end(), std::bind2nd(std::tr1::mem_fn(&Widget::test), 0));
return 0;
}
さて、ここでコンテナの要素をWidget*からstd::tr1::shared_ptr答えはコンパイルエラーです。
std::list<std::tr1::shared_ptr<Widget> > lspw; std::for_each(lspw.begin(), lspw.end(), std::bind2nd(std::mem_fun(&Widget::test), 0)); // compile error. std::for_each(lspw.begin(), lspw.end(), std::bind2nd(std::tr1::mem_fn(&Widget::test), 0)); // compile error.それでは、ここでstd::tr1::bindの出番です。
#include <list>
#include <algorithm>
#include <functional>
#include <tr1/memory>
#include <tr1/functional>
class Widget {
public:
void test(int n) {}
};
int main()
{
using namespace std::tr1::placeholders;
std::list<std::tr1::shared_ptr<Widget> > lspw;
std::for_each(lspw.begin(), lspw.end(), std::tr1::bind(&Widget::test, _1, 0));
return 0;
}
素晴らしいことに、std::mem_funもstd::tr1::mem_fnも必要ありません。最後に、メンバ関数test()に第2引数が追加された場合、どうなるでしょうか?
答えはstd::tr1::bindに引数を追加するだけです。
#include <list>
#include <algorithm>
#include <functional>
#include <tr1/memory>
#include <tr1/functional>
class Widget {
public:
void test(int n, const char* text) {}
};
int main()
{
using namespace std::tr1::placeholders;
std::list<std::tr1::shared_ptr<Widget> > lspw;
std::for_each(lspw.begin(), lspw.end(), std::tr1::bind(&Widget::test, _1, 0, ""));
return 0;
}

