【问题标题】:Pass an unary predicate to a function in C++将一元谓词传递给 C++ 中的函数
【发布时间】:2009-07-01 06:26:55
【问题描述】:

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

SetDisplayPolicy(BOOLEAN_PRED_T f)

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

typedef bool (*BOOLEAN_PRED_T) (int);

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

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

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

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

这是个好方法吗?

【问题讨论】:

    标签: c++ stl arguments predicate


    【解决方案1】:

    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 继承,它做同样的事情,还会为您购买两个 typedefs argument_typeresult_type

    【讨论】:

    • 对于那些在 2015 年及以后阅读这篇文章的人......使用通用 std::function 而不是 std::unary_function 可能会更好,因为后者将在 C 中被弃用++17
    【解决方案2】:

    你在正确的轨道上,因为 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 2013-11-18
      • 2018-07-07
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多