为std模板函数创建函子对象时减少样板 [英] Reducing boilerplate when creating functor objects for std template functions

查看:87
本文介绍了为std模板函数创建函子对象时减少样板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为另一个问题的解决方案,创建包含各种标准(可能还有其他内容)的通用仿函数对象似乎很有用。

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.

这些函数有时比相应的模板函数更有用,因为该函数的特定类型在传递时绑定晚作为仿函数对象:仅在被调用方内的调用站点上,而不在调用方上。例如,您不能将 std :: min 作为函子对象,必须传递类似于 std :: min< int> ,这意味着被叫方无法对多种同类型的数据进行操作。

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.

另一方面,您可以传递 min_functor ,如下所示,将在被叫方的每个呼叫方选择 min 的右实例。

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); }
};

最后,问题是:我是否想为诸如 max 等等,除了宏 1 之外,有没有其他方法可以复制上面的样板?

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 宏似乎在这里可以很好地工作,但是我不忍面对强大的反宏的嘲笑大厅。

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.

推荐答案

,因为没有立即就不能命名功能模板上下文,它标识了它的专业化。 (考虑模板模板参数必须是类模板或别名模板。)但是,有一些警告:

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. 几种语法来实现已被提出

  2. 可以将函数模板作为参数传递给函数指针(以没有状态且可能没有内联为代价)的参数作为参数。 / li>
  3. 某些现代设计使用功能对象 ,虽然实际上只是提前包含了相同的样板。

  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.

这篇关于为std模板函数创建函子对象时减少样板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆