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

Her*_*nán 2 c++ arguments stl predicate

我需要一个为我的类建立一个显示项目的策略的函数.例如:

SetDisplayPolicy(BOOLEAN_PRED_T f)
Run Code Online (Sandbox Code Playgroud)

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

typedef bool (*BOOLEAN_PRED_T) (int);
Run Code Online (Sandbox Code Playgroud)

我只对以下内容感兴趣:当传递的谓词为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>{};
Run Code Online (Sandbox Code Playgroud)

这可能是一个好方法吗?

csj*_*csj 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
    }
}
Run Code Online (Sandbox Code Playgroud)


Ari*_*Ari 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.
}
Run Code Online (Sandbox Code Playgroud)

然后使用:

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

SetDisplayPolicy(MyPredClass());
Run Code Online (Sandbox Code Playgroud)

在显示代码中,您将需要进行以下操作:

if(myPred(/* whatever */)
   Display();
Run Code Online (Sandbox Code Playgroud)

当然,您的函子可能需要具有状态,并且您可能希望其构造函数执行操作等。关键是SetDisplayPolicy,只要您可以粘贴函数调用,它就不在乎您提供的内容(包括函数指针)到它上并得到一个bool

编辑:而且,正如csj所说,您可以继承STL的功能unary_function,而STL的功能相同,也可以购买两个typedefs argument_typeresult_type