2

我需要一个函数来为我的班级建立一个显示项目的策略。例如:

SetDisplayPolicy(BOOLEAN_PRED_T f)

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

typedef bool (*BOOLEAN_PRED_T) (int);

我只对例如感兴趣:当传递的谓词为真时显示某些内容,当它为假时不显示。

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

我想将我自己的类型派生为:

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

这会是一个好方法吗?

4

2 回答 2

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
    }
}
于 2009-07-01T06:49:20.743 回答
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.

Edit: And, as csj said, you could inherit from STL's unary_function which does the same thing and will also buy you the two typedefs argument_type and result_type.

于 2009-07-01T06:50:48.057 回答