Reducing boilerplate when creating functor objects for std template functions

走远了吗. 提交于 2019-12-13 17:57:25

问题


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:

  1. Several syntaxes to do so have been proposed.
  2. 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).
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!