问题
As a solution to another question it seems useful to create "generic functor objects" which wrap various standard (and perhaps user-defined) template functions in a functor object.
These are sometimes more useful than the corresponding template functions because the specific type of the function is "bound late" when passed as a functor object: only at the call site within the callee, rather than at the caller. For example, you cannot pass std::min
as a functor object, you must pass a instantiation like std::min<int>
which means the callee cannot operate on a variety of homogenous types.
On the other hand, you can pass min_functor
as shown below and the right instantiation of min
will be chosen at each call side in the callee.
struct min_functor {
template <typename T>
const T& operator()(const T& l, const T& r) const { return std::min(l,r); }
};
Finally, the question: if I want to define several of these for various binary operations like max
and so on, is there some way to do it without copying the boilerplate above, other than macros1?
1 It seems like macros would work pretty well here, but I can't bear to face the scorn of the powerful anti-macro lobby.
回答1:
No, because you can’t name a function template without immediate context that identifies a specialization of it. (Consider that template template arguments must be class or alias templates.) There are several caveats, however:
- Several syntaxes to do so have been proposed.
- A function template can be passed as an argument for a parameter that is a function pointer (at the cost of no state and probably no inlining).
- Some modern designs use function objects directly, although this is really just including the same boilerplate ahead of time.
来源:https://stackoverflow.com/questions/55987832/reducing-boilerplate-when-creating-functor-objects-for-std-template-functions