简体   繁体   中英

Way to keep template inference in C++03 with function objects?

I would like to provide a (templated) function taking (among other) a function-ish object with a given return type as an argument, and ideally I would like to be able to call that function without explicit template arguments.

So far I tried:

template<A, B, F>
B some(A a, F f) { return f(a); }

template<A, B>
B some(A a, B (*f)(A)) { return some<A, B, B (*)(A)>(a, f); }

Where I have the overload to make the template args fully inferable, at least for function pointers. Now it seems I can't make the template specialization for std::unary_function , since it doesn't contain the operator() member and so it is not suitable as F .

Moreover, it seems there isn't any solution for functors in general, since I can't inform the compiler that I want F to have B operator()(A) . Or is such duck typing possible somehow?

std::unary_function is just a base for other classes with should provide operator() . There should be no instances of unary_function at all, so I can't see the problem - the first function taking 3 template arguments is the official solution for such problems.

edit: If you wanna call that function without explicit template arguments, than use std::result_of (C++11) or boost::result_of .

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