Created
November 5, 2012 07:16
-
-
Save alexeiz/4015773 to your computer and use it in GitHub Desktop.
Lambda overload set
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
template <typename ...Funcs> | |
struct overload_set; | |
template <typename Head, typename ...Tail> | |
struct overload_set<Head, Tail...> : Head, overload_set<Tail...> | |
{ | |
overload_set(Head head, Tail... tail) | |
: Head{head} | |
, overload_set<Tail...>{tail...} | |
{} | |
using Head::operator(); | |
using overload_set<Tail...>::operator(); | |
}; | |
template <typename Func> | |
struct overload_set<Func> : Func | |
{ | |
overload_set(Func func) | |
: Func{func} | |
{} | |
using Func::operator(); | |
}; | |
template <typename ...Funcs> | |
overload_set<Funcs...> overload(Funcs... funcs) | |
{ | |
return overload_set<Funcs...>{funcs...}; | |
} | |
int main() | |
{ | |
auto f = overload( | |
[] { return 1; }, | |
[] (int x) { return x + 1; }, | |
[] (double x) { return 2 * x; } | |
); | |
using std::cout; | |
using std::endl; | |
cout << f() << endl | |
<< f(1) << endl | |
<< f(2.0) << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment