c++ - implementing a generic binary function with a class and functor as template parameters -
c++ - implementing a generic binary function with a class and functor as template parameters -
i trying wrap templated functions binary functors below. when seek compile code have error
error: no match phone call ‘(qtyasc) (myobj&, myobj&)
i thought beingness operator()
in qtyasc
function in class, template deduction mechanism have worked seems compiler doesn't take myobj
classes valid types it.
is maybe because of phone call boost::bind
? trying provide default implementation sec templated argument (unfortunately cannot utilize c++11 default templated arguments).
class myobj { public: myobj(int val) : qty_(val) {} int qty() { homecoming 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) { homecoming 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)) homecoming true; homecoming false; } }; int main() { myobj t1(10),t2(20); qtyasc asc; if(asc(t1,t2)) cout << "yes" << endl; }
if can't utilize c++11, provide additional overload:
struct qtyasc { template<class t, class qex > bool operator()(const t& o1, const t& o2, qex extr) const { homecoming extr(o1) < extr(o2); } template<class t> bool operator()(const t& o1, const t& o2) const { homecoming operator()(o1, o2, &get_quantity<t>); } };
(i've omitted unnecessary boost::bind
.) also, need declare myobj::qty
const
:
int qty() const { homecoming qty_; }
since want invoke on const
objects. (live demo)
c++ templates function-templates
Comments
Post a Comment