samedi 4 mai 2019

Reducing boilerplate when creating functor objects for std template functions

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.

Aucun commentaire:

Enregistrer un commentaire