1. 程式人生 > >boost—— 函式與回撥function

boost—— 函式與回撥function

/*function是一個函式物件的"容器",它以物件的形式封裝了原始的函式指標或函式物件,
 * 能夠容納任意符合函式簽名的可呼叫物件。function也是一個大的類家族,可以容納0
 * -10個引數的函式,有多達11個類,分別是function1...function10。
 *
 * function使用result_of的方式,因此我們不需要再模板引數列表中寫出被容納函式原型
 * 的返回值和所有函式引數的型別。例如:
 * function<int()> func;    //聲明瞭一個返回值為int,無參的function物件
 * 若編譯器不相容,可以採用相容語法,在function類名中指定引數數量:
 * 例如:
 * 1.function0<int>  func;
 * 2.function3<int int,int,int> func2
 *
 * function摘要:
 * template<typename Signature>
 * class function:public functionN<R,T1,T2...,,TN>
 * {
 *  public:
 *      //內部型別定義
 *      typedef R result_type;
 *      typedef TN argN_type;
 *      //引數個數數量
 *      static const int arity = N;
 *      //建構函式
 *      function();
 *      template<typename F> function(F);
 *      //基本操作
 *      void swap(const function&);
 *      void clear();
 *      bool empty() const;
 *      operator safe_bool() const;
 *      bool operator!() const;
 *      //訪問內部元素
 *      template<typename Functor> Functor* target();
 *      template<typename Functor> const Functor* target() const;
 *      template<typename Functor> bool contains(const Functor&) const;
 *      const std::type_info& target_type() const;
 *      result_type operator()(arg1_type,...,argN_type) const;
 *
 * };
 * */
#include <iostream> #include <string> #include <vector> #include <set> #include <map> #include <algorithm> #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/ref.hpp> #include <boost/assign.hpp> using namespace boost::assign; using
namespace boost; using namespace std; int f(int a,int b) { return (a + b); } struct demo_class { int add(int a,int b) { return (a+b); } int operator()(int x) const { return (x*x); } }; template<typename T> struct summary { typedef void
result_type; T sum; summary(T v = T()):sum(v){ } void operator()(T const& x) { sum += x; } }; int main( int argc,char **argv) { /*比較操作: * 過載了"=="和"!="操作符*/ function<int(int,int)> func(f); assert(func == f); if(func) { cout << func(10,90) << endl; } func = 0; assert(func.empty()); //function清空,相當於clear //在函式型別中僅寫出成員函式的簽名,bind時直接繫結類的例項 function<int (int,int)> func1; demo_class sc; func1 = bind(&demo_class::add,&sc,_1,_2); cout << func1(10,20) << endl; //在宣告函式型別時直接指定類的型別,然後bind繫結 function<int(demo_class&,int,int)> func2; func2 = bind(&demo_class::add,_1,_2,_3); cout << func2(sc,20,30) << endl; /*function直接呼叫ref包裝的函式物件*/ vector<int> iv = list_of(1)(2)(3)(4); summary<int> s; //有狀態的函式物件 function<void(int const&)> func10(ref(s)); //function包裝引用 std::for_each(iv.begin(),iv.end(),func10); cout << s.sum << endl; //函式物件的狀態被改變 return (0); }