简体   繁体   中英

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

I am trying to wrap some templated functions into some binary functors like below. When I try to compile the code I have the error

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

I thought that being operator() in QtyAsc a function in a class, the template deduction mechanism would have worked but it seems that the compiler doesn't accept myobj classes as valid types for it.

Is it maybe because of the call to boost::bind ? I was trying to provide a default implementation for the second templated argument (unfortunately I cannot use C++11 with default templated arguments).

  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;
   }

If you can't use C++11, just provide an additional overload:

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>);
  }
};

(I've omitted the unnecessary boost::bind .) Also, you will need to declare myobj::qty to be const :

int qty() const {
  return qty_;
}

since you want to invoke it on const objects. ( Live demo )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM