Bulat
Bulat

Reputation: 2466

How to pass generic lambda into function

I have the following C++ code:

template <class T1, class T2, class T3>
void MetaTypeHandler(T1 lambda1, T2 lambda2, T3 lambda3) {
 lambda1(1);
 lambda2('x');
 lambda3(true);
}

int main() {
  auto f = [] (auto x) {};
  MetaTypeHandler(f,f,f);
}

Passing f multiple times is ugly. Is it possible to write MetaTypeHandler() so that f is passed only 1 or 2 times? I think that template template parameters may help, but can't wrap my head around them.

Upvotes: 3

Views: 1314

Answers (2)

StPiere
StPiere

Reputation: 4243

You can just provide an overload:

#include <iostream>

template <class T1, class T2, class T3>
void MetaTypeHandler(T1 lambda1, T2 lambda2, T3 lambda3) {
 lambda1(1);
 lambda2('x');
 lambda3(true);
}

template <class T>
void MetaTypeHandler(T lambda)
{
    MetaTypeHandler(lambda, lambda, lambda);
}

int main() {
  auto f = [] (auto x) {std::cout << x << std::endl;};
  MetaTypeHandler(f);
}

So you can pass 3 different handlers, or one handler executing 3 times.

Live

Upvotes: 2

max66
max66

Reputation: 66200

I don't understand the problem.

It's a generic lambda.

Substantially the object of a struct with a template operator() in it.

So you can pass it one time only and use it with all types you want

#include <iostream>

template <typename T>
void MetaTypeHandler (T lambda)
 {
   lambda(42);
   lambda('x');
   lambda("abc");
   lambda(true);
 }

int main()
 {
   MetaTypeHandler(
      [](auto const & x){ std::cout << "x is " << x << std::endl;});
 }

Upvotes: 6

Related Questions