i have been looking @ of boost source code , noticed implement templated functions using functor instead of plain function? there reason this?
for example:
template<typename foo, typename bar> struct functor { bar operator()(const foo& foo) { return foo.as_bar(); } }; as opposed to:
template<typename foo, typename bar> bar func(const foo& foo) { return foo.as_bar(); } the advantage can come allows classes inherit function?
there 2 main reasons: first is, pythonic metaphor noted, partial specialization valid classes , not functions. note functions can use overloads overcome problem generally, if doing metaprogramming it's easier , more generic use partial specialization. i'd think main reason.
the second reason anytime code wants accept function object (like in stl, e.g. std::transform), have type template parameter. if pass functor or lambda, exact type known @ compile time, , don't pay indirection, , inlining can performed. if pass function pointer (or std::function), signature known @ compile time, , pay indirection (and can't inline). instance, std::sort can considerably faster functor function pointer.
note there little used feature called function pointer template parameters; these non type template parameters specialize on specific function, , can remove indirection. however, if use 1 of these, can't use functor @ all. code wants accepts function object way described above.
Comments
Post a Comment