Search code examples
c++templateslambdageneric-lambda

Method template as functor


I have a container class template containing members of several different types. I would like to pass a functor which is called for each of the elements. I can do what I want with the following code:

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

}

While defining structs with a template operator() works, I am missing the comfort we have when defining a lambda function. 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)?


Solution

  • 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)?

    Sure.

    But only starting from C++14 (that introduce generic lambdas)

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