What else do I need to use variation pattern inheritance to create lambda overloads?

I understand the basic concept of using the recursive nature of the parameters of a variational template and a specific instance of a template to sort β€œeat” my path through the list of parameters one by one.

I understand that lambdas can be written to take certain types and then return certain types. Keep in mind that I'm still learning C ++ 14 and C ++ 11, so I have not mastered one or the other.

Here is my attempt after looking at other stack overflow questions :

// For std::string #include <string> // For std::cout #include <iostream> //Create a generalized list instantiation template <typename ... F> struct overload : public F... { overload(F... f) : F(f)... {} }; //Create an specific end-case, where we directly //inherit the () operator in order to inherit //multiple () overloads template <typename F> struct overload : F { using F::operator(); }; //template function to create an overload template <class... F> auto make_overload(F... f) { return (f...); } int main() { auto f = [](int x,int y) -> int { return x+y; }; auto g = [](double x,double y) -> int { return std::ftoi(x+y); }; auto h = [](std::string x,std::string y) -> int { return std::stoi(x+y); }; //Ah, but this is a function. auto fgh = make_overload(f,g,h); std::cout << (fgh(1,2)) << std::endl; std::cout << (fgh(1.5,2.5)) << std::endl; std::cout << (fgh("bob","larry")) << std::endl; } 

Coliru: http://coliru.stacked-crooked.com/a/5df2919ccf9e99a6

What am I conceptually missing here? Other answers may briefly answer this problem at face value, but I am looking for an explanation of why the answer eludes my thinking. If I understand what I need to do using F::operator() to inherit the operators, and I correctly assert that the return types and parameters are different, what else needs to be done to make this work?

Here is my train of thought:

  • Create a common varadic template base class.
  • Create a specific template case to overload a specific lambda operator() .
  • Create a helper function to take the argument list of the variational pattern and then use it to create the overload class.
  • Make sure the types are unambiguous.
+5
source share
1 answer

You really haven't bought it.

 // primary template; not defined. template <class... F> struct overload; // recursive case; inherit from the first and overload<rest...> template<class F1, class... F> struct overload<F1, F...> : F1, overload<F...> { overload(F1 f1, F... f) : F1(f1), overload<F...>(f...) {} // bring all operator()s from the bases into the derived class using F1::operator(); using overload<F...>::operator(); }; // Base case of recursion template <class F> struct overload<F> : F { overload(F f) : F(f) {} using F::operator(); }; 
+4
source

All Articles