Skip to content

Instantly share code, notes, and snippets.

@daniel-j-h
Last active October 26, 2016 16:57
Embed
What would you like to do?
Lambdas instead of visitors

The MIT License (MIT)

Copyright (c) 2016 Daniel J. Hofmann

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include <string>
#include <iostream>
#include <boost/variant.hpp>
template <typename Left, typename Right>
using Either = boost::variant<Left, Right>;
struct Response {};
struct Error {};
// Option 1: write visitor and feel the pain in your fingers
struct Match {
std::string operator()(Response) const { return "ok"; }
std::string operator()(Error) const { return "error"; }
};
// Option 2: let compiler synthesize a visitor based on lambdas
template <typename... Fns> struct Combined;
template <typename Fn>
struct Combined<Fn> : Fn {
using type = Fn;
Combined(Fn fn) : Fn(fn) { }
using Fn::operator();
};
template <typename Fn, typename... Fns>
struct Combined<Fn, Fns...> : Fn, Combined<Fns...>::type {
using type = Combined;
Combined(Fn fn, Fns... fns) : Fn(fn), Combined<Fns...>::type(fns...) { }
using Fn::operator();
using Combined<Fns...>::type::operator();
};
template <typename... Fns>
typename Combined<Fns...>::type match(Fns... fns) {
return Combined<Fns...>(fns...);
}
// Usage
int main(int argc, char** /*argv*/) {
Either<Error, Response> rv;
if (argc == 2)
rv = Response{};
else
rv = Error{};
// For Option 1, the visitor and its invocation is separated
std::cout << apply_visitor(Match{}, rv) << std::endl;
// Option 2, hey this almost looks like Haskell/Swift/Rust :)
auto handler = match([] (Response) { return "ok"; },
[] (Error) { return "error"; });
std::cout << apply_visitor(handler, rv) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment