C++中仿函數的應用

字號:

使用仿函數的時候,主要用到以下兩種:一種是以基類std::unary_function派生出來的派生類;另一種是以基類std::binary_function派生出來的派生類。而這兩種有什么區(qū)別呢?它們之間的區(qū)別只是第一種接收的參數個數為一個,而第二種接收的參數的個數為兩個。而已。
    好了,我們還是來幾個例子看看:
    第一種的使用
    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提示: 上面所說的接收參數的個數也就是仿函數里面的重定義函數調用操作符中的所接收的參數個數于類型,他們是相一致的。
    上面是介紹stl庫中的仿函數,而另外一個庫中也有仿函數(Loki庫),如果想詳細其中的實現,可以下載Loki庫來進行研究。
    你在進行讀Loki庫中的Functor的時候,必須首先要了解那段火星代碼,也就是Typelist,這個是整個泛型編程的精髓,實現了模板的完美遞歸。