作为函数的方法模板

Method template as functor

我有一个容器 class 模板,其中包含几种不同类型的成员。我想传递一个为每个元素调用的函子。我可以用下面的代码做我想做的事:

#include <iostream>

template <typename T1, typename T2>
class MyContainer
{
public:
  template <typename Op>
  void run_operation(Op op)
  {
    op(t1);
    op(t2);
  }

  T1 t1;
  T2 t2;


};

struct OutputOperation
{
  template <typename T>
  void operator()(T t)
  {
    std::cout << "value is " << t << std::endl;
  }
};

int main() {
  MyContainer<int, double> container;
  OutputOperation out_op;
  container.run_operation(out_op);

}

虽然使用模板 operator() 定义结构是可行的,但我失去了定义 lambda 函数时的舒适感。有什么方法可以使用 lambda 函数来实现与结构相同的效果吗?或者至少允许我在调用方法中定义操作的东西(使用模板是不可能的)?

Is there any way to use lambda functions to achieve the same effect as with the struct? Or at least something that allows me to define the operation inside the calling method (which is not possible with templates)?

当然可以。

但仅从 C++14(引入通用 lambda)开始

  container.run_operation(
     [](auto t){ std::cout << "value is " << t << std::endl; });