2

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

max66
  • 65,235
  • 10
  • 71
  • 111
Philipp
  • 11,549
  • 8
  • 66
  • 126
  • 1
    Wouldn't `std::function` work for you? You can pass a lambda (and more) to such. – Jesper Juhl May 06 '19 at 17:25
  • 1
    @JesperJuhl a templated parameter is generally a better idea if you don't need to actually store the function. `std::function` implements type erasure and it's generally a better idea to use a type directly instead. – Guillaume Racicot May 06 '19 at 18:13

1 Answers1

6

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; });
max66
  • 65,235
  • 10
  • 71
  • 111