传递通用函数以对同类类型进行操作 [英] Passing a generic function to operate on homogenous types

查看:49
本文介绍了传递通用函数以对同类类型进行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个由同类构成的类:

Let's say I have a class composed of homogeneous types:

struct Homog {
    int a;
    double b;
    std::string c;
};

这是一个函数,可计算以下项的元素最小值 1 此类的两个实例:

Here's a function which calculates the "element-wise min"1 of two instances of this class:

Homog min(const Homog& l, const Homog& r) {
  return {
      std::min(l.a, r.a),
      std::min(l.b, r.b),
      std::min(l.c, r.c),
  };
}

很棒。

现在我要计算 max 而不是 min 。该代码是相同的,但是用 std :: max 替换了 std :: min 。我不想重复它,而是想使用一个通用的按元素应用方法,然后用适当的函子来调用min和max:

Now I want to calculate the max instead of the min. The code is identical, but with std::min replaced with std::max. I wouldn't want to duplicate it, rather I'd like to have one generic "element-wise apply" method, and then the min and max just call that with the appropriate functor:

Homog apply(const Homog& l, const Homog& r, ?? op) {
  return {
      op(l.a, r.a),
      op(l.b, r.b),
      op(l.c, r.c),
  };
}

Homog min(const Homog& l, const Homog& r) {
    return apply(l, r, std::min);
}

Homog max(const Homog& l, const Homog& r) {
    return apply(l, r, std::max);
}

当然,上面的代码不起作用,因为我不知道如何声明 op 。它不是普通的泛型仿函数对象,因为它需要处理不同的类型。

Of course, the above code doesn't work, because I don't know how to declare op. It is not a normal generic functor object, because it needs to work on different types.

我可以做我想做的事情吗,以某种方式传递调用op for每个成员:不用担心,每种类型都会解析为某种东西?

Can I do what I want to, somehow passing something which says "call op for each member: don't worry, it will resolve to something for each type"?

也许使用 min()不是这里的最佳名称,因为它的行为与 std :: min 相同,后者总是返回一个给定的两个对象中的一个:此方法返回一个新对象,该对象通常与两个输入中的任何一个都不相同,而是它们的成员值的混合。

Maybe using min() isn't the best name here, because it doesn't behave the same as std::min which always returns one of the two given objects: this method returns a new object which in general is not the same as either of the two inputs, but rather a mix of their member values.

推荐答案


当然,上面的代码不起作用,因为我不知道如何声明op。它不是普通的泛型仿函数对象,因为它需要处理不同的类型。

Of course, the above code doesn't work, because I don't know how to declare op. It is not a normal generic functor object, because it needs to work on different types.

通常使用功能来绕过此问题,使用模板 operator()

This problem is usually bypassed using a functional, with a template operator().

从C ++ 14(引入通用lambda)开始,如下所示

Starting from C++14 (that introduce generic lambdas) simply as follows

template <typename F>
Homog apply(const Homog& l, const Homog& r, F const & op) {
  return {
      op(l.a, r.a),
      op(l.b, r.b),
      op(l.c, r.c),
  };
}

Homog min(const Homog& l, const Homog& r) {
    return apply(l, r, [](auto const & a, auto const & b){ return std::min(a, b); });
}

这篇关于传递通用函数以对同类类型进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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