Created
August 29, 2013 19:53
-
-
Save evincarofautumn/6382635 to your computer and use it in GitHub Desktop.
Overloaded lambdas in C++11.
This file contains 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> | |
#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