用类和函子作为模板参数实现一个泛型二进制函数

implementing a generic binary function with a class and functor as template parameters

本文关键字:一个 函数 二进制 泛型 实现 参数      更新时间:2023-10-16

我试图将一些模板函数包装成一些二进制函数,如下所示。当我尝试编译代码时,我有错误

 error: no match for call to ‘(QtyAsc) (myobj&, myobj&)

我认为QtyAsc中的operator()是一个类中的函数,模板演绎机制会起作用,但似乎编译器不接受myobj类作为它的有效类型。

可能是因为呼叫boost::bind ?我试图为第二个模板化参数提供默认实现(不幸的是,我不能使用带有默认模板化参数的c++ 11)。

  class myobj {
   public:
    myobj(int val) : qty_(val) {}
    int qty() { return qty_;}
   private:
    int qty_;
  };
  template<class T>
  int get_quantity(const T& o) {
    throw runtime_error("get_quantity<T> not implemented");
  }
  template<>
  int get_quantity(const myobj& o) {
    return o.qty();
  }
  struct QtyAsc {
    template<class T, class QEx >
    bool operator()(const T& o1, const T& o2, QEx extr = boost::bind(&get_quantity<T>,_1)) const {
      if(extr(o1) < extr(o2))
        return true;
      return false;  
    }
  };
  int main() {
   myobj t1(10),t2(20);
   QtyAsc asc;
    if(asc(t1,t2))
      cout << "Yes" << endl;
   }

如果不能使用c++ 11,只需提供额外的重载:

struct QtyAsc {
  template<class T, class QEx >
  bool operator()(const T& o1, const T& o2, QEx extr) const {
    return extr(o1) < extr(o2);
  }
  template<class T>
  bool operator()(const T& o1, const T& o2) const {
    return operator()(o1, o2, &get_quantity<T>);
  }
};

(我省略了不必要的boost::bind。)另外,您需要将myobj::qty声明为const:

int qty() const {
  return qty_;
}

,因为您想在const对象上调用它。(现场演示)