2009-07-01 21 views
2

我需要一個函數來爲我的類創建一個用於顯示項目的策略。例如:將一個一元謂詞傳遞給C++中的一個函數

SetDisplayPolicy(BOOLEAN_PRED_T f) 

這是假設BOOLEAN_PRED_T是函數指針一些布爾謂詞類型,如:

typedef bool (*BOOLEAN_PRED_T) (int); 

我感興趣的只是在如:顯示的東西時,所傳遞的謂詞是真,當它是假的時候不顯示。

上面的例子適用於函數返回布爾和採取一個int,但我需要一個非常通用的指針SetDisplayPolicy參數,所以我想到UnaryPredicate,但它是與增強相關的。我如何將一元謂詞傳遞給STL/C++中的函數? unary_function< bool,T >將無法​​正常工作,因爲我需要一個bool作爲返回值,但我想要求用戶只用於「一元函數返回布爾」,在最通用的方法。

我想獲得我自己的類型爲:

template<typename T> 
class MyOwnPredicate : public std::unary_function<bool, T>{}; 

莫非是一個好方法?

回答

4

打開SetDisplayPolicy成函數模板:

template<typename Pred> 
void SetDisplayPolicy(Pred &pred) 
{ 
    // Depending on what you want exactly, you may want to set a pointer to pred, 
    // or copy it, etc. You may need to templetize the appropriate field for 
    // this. 
} 

即可使用,做到:

struct MyPredClass 
{ 
    bool operator()(myType a) { /* your code here */ } 
}; 

SetDisplayPolicy(MyPredClass()); 

在顯示代碼你會有點像:

if(myPred(/* whatever */) 
    Display(); 

當然,你的函子可能需要有一個狀態,你可能想要它的構造函數做東西,等等。關鍵是SetDisplayPolicy不在乎你給它(包括函數指針),只要你可以粘一個函數調用它並返回一個bool

編輯:而且,正如CSJ說,你可以從STL的unary_function這做同樣的事情繼承,也給你買兩個typedef小號argument_typeresult_type

+0

對於那些在2015年及以後閱讀的人來說......使用通用std :: function <>代替std :: unary_function <>可能會更好,因爲後者將在C++ 17中被棄用 – plexoos 2015-10-13 02:22:01

5

由於unary_function是作爲基類使用的,因此您處於正確的軌道。但是請注意,第一個參數應該是argument_type,第二個參數是result_type。然後,所有你需要做的是實現operator()

template<typename T> 
struct MyOwnPredicate : public std::unary_function<T,bool> 
{ 
    bool operator() (T value) 
    { 
     // do something and return a boolean 
    } 
} 
相關問題