Skip to content

Instantly share code, notes, and snippets.

@evincarofautumn
Created August 29, 2013 19:53
Show Gist options
  • Save evincarofautumn/6382635 to your computer and use it in GitHub Desktop.
Save evincarofautumn/6382635 to your computer and use it in GitHub Desktop.
Overloaded lambdas in C++11.
#include <iostream>
#include <string>
#include <utility>
using namespace std;
template<class... Fs> struct Overload;
template<class F, class... Fs>
struct Overload<F, Fs...> : Overload<Fs...> {
Overload(F&& f, Fs&&... fs)
: Overload<Fs...>(forward<Fs>(fs)...),
function(move(f)) {}
template<class... Args>
auto operator()(Args&&... args) const
-> decltype(declval<F>()(forward<Args>(args)...)) {
return function(forward<Args>(args)...);
}
using Overload<Fs...>::operator();
private:
F function;
};
template<> struct Overload<> { void operator()() const {} };
template <class... Fs>
Overload<Fs...> make_overload(Fs&&... fs) { return { forward<Fs>(fs)... }; }
int main() {
auto overload = make_overload(
[](const string& s) { return "string: " + s; },
[](int i) { return "int: " + to_string(i); }
);
cout << overload(1) << '\n';
cout << overload("hi") << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment