3

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.

0

2 Answers 2

6

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;});
 }
Sign up to request clarification or add additional context in comments.

3 Comments

"struct with a template operator() in it" - thanks, now I got it. I really should learn C++ once :D
@JVApen thank you very much! Looks that this site may help me in many situations
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.