Skip to content

Instantly share code, notes, and snippets.

@alexeiz
Created November 5, 2012 07:16
Show Gist options
  • Save alexeiz/4015773 to your computer and use it in GitHub Desktop.
Save alexeiz/4015773 to your computer and use it in GitHub Desktop.
Lambda overload set
#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