2009-07-01 73 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 
    } 
} 
相关问题