使用仿函數(shù)的時候,主要用到以下兩種:一種是以基類std::unary_function派生出來的派生類;另一種是以基類std::binary_function派生出來的派生類。而這兩種有什么區(qū)別呢?它們之間的區(qū)別只是第一種接收的參數(shù)個數(shù)為一個,而第二種接收的參數(shù)的個數(shù)為兩個。而已。
好了,我們還是來幾個例子看看:
第一種的使用
template
class MeetsThreshold: public std::unary_function{
private:
const T threshold;
public:
MeetsThreshold(const T& threshold);
bool operator()(const Widget&) const;
...
};
第二種的使用
struct WidgetNameCompare:
public std::binary_function{
bool operator()(const Widget& lhs, const Widget& rhs) const;
};
examda提示: 上面所說的接收參數(shù)的個數(shù)也就是仿函數(shù)里面的重定義函數(shù)調(diào)用操作符中的所接收的參數(shù)個數(shù)于類型,他們是相一致的。
上面是介紹stl庫中的仿函數(shù),而另外一個庫中也有仿函數(shù)(Loki庫),如果想詳細(xì)其中的實現(xiàn),可以下載Loki庫來進行研究。
你在進行讀Loki庫中的Functor的時候,必須首先要了解那段火星代碼,也就是Typelist,這個是整個泛型編程的精髓,實現(xiàn)了模板的完美遞歸。
好了,我們還是來幾個例子看看:
第一種的使用
template
class MeetsThreshold: public std::unary_function
private:
const T threshold;
public:
MeetsThreshold(const T& threshold);
bool operator()(const Widget&) const;
...
};
第二種的使用
struct WidgetNameCompare:
public std::binary_function
bool operator()(const Widget& lhs, const Widget& rhs) const;
};
examda提示: 上面所說的接收參數(shù)的個數(shù)也就是仿函數(shù)里面的重定義函數(shù)調(diào)用操作符中的所接收的參數(shù)個數(shù)于類型,他們是相一致的。
上面是介紹stl庫中的仿函數(shù),而另外一個庫中也有仿函數(shù)(Loki庫),如果想詳細(xì)其中的實現(xiàn),可以下載Loki庫來進行研究。
你在進行讀Loki庫中的Functor的時候,必須首先要了解那段火星代碼,也就是Typelist,這個是整個泛型編程的精髓,實現(xiàn)了模板的完美遞歸。