将一元谓词传递给C ++中的函数

时间:2009-07-01 06:26:55

标签: c++ stl arguments predicate

我需要一个为我的班级建立一个显示项目的策略的函数。 e.g:

SetDisplayPolicy(BOOLEAN_PRED_T f)

这假设BOOLEAN_PRED_T是某个布尔谓词类型的函数指针,如:

typedef bool (*BOOLEAN_PRED_T) (int);

我只对以下内容感兴趣:当传递的谓词为TRUE时显示某些东西,当它为假时不显示。

上面的例子适用于返回bool和取一个int的函数,但是我需要一个非常通用的指针用于SetDisplayPolicy参数,所以我想到了UnaryPredicate,但它与boost相关。如何将一元谓词传递给STL / C ++中的函数? unary_function< bool,T >将无法工作,因为我需要一个bool作为返回值,但我想要用户通过“最常用的方法”来查询“返回bool的一元函数”。

我想把我自己的类型推导为:

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

这可能是一个好方法吗?

2 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:5)

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 s {{1} }和argument_type