c++ - 作为仿函数的方法模板

标签 c++ templates lambda generic-lambda

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

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

关于c++ - 作为仿函数的方法模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56009743/

相关文章:

c++ 指向嵌套类成员函数的指针

qt - 将 lambda 函数连接到 QProcess::error 时出错

java - 为什么 lambda 调用有 2 个堆栈帧?

c++ - 函数参数中的 Typedef 等价

c++ - 无法推断重载函数的模板参数

c++ - 为什么 C++ 编译器可以将函数声明为 constexpr,而不能是 constexpr?

lambda - 不能将函数调用用作 s-exp 中的第一个参数

c++ - 从函数获取输出动态分配数组的更好变体?

c++ - 修改递归子集求和算法

c# - “C++ void Pointer”和 “C# var”之间的区别