overload_linearly.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Copyright Louis Dionne 2013-2017
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
  4. #include <boost/hana/assert.hpp>
  5. #include <boost/hana/equal.hpp>
  6. #include <boost/hana/find_if.hpp>
  7. #include <boost/hana/optional.hpp>
  8. #include <boost/hana/transform.hpp>
  9. #include <boost/hana/tuple.hpp>
  10. #include <boost/hana/type.hpp>
  11. #include <string>
  12. namespace hana = boost::hana;
  13. // We have an utility in the Functional module that does pretty much the
  14. // same, but is more compile-time efficient. It is still interesting to
  15. // see this implemented with sequences and the SFINAE combinator.
  16. auto overload_linearly = [](auto ...candidates) {
  17. return [=](auto ...args) {
  18. auto maybe_function = hana::find_if(hana::make_tuple(candidates...), [=](auto f) {
  19. return hana::is_valid(f)(args...);
  20. });
  21. auto result = hana::transform(maybe_function, [=](auto f) {
  22. return f(args...);
  23. });
  24. return result;
  25. };
  26. };
  27. int main() {
  28. auto f = ::overload_linearly(
  29. [](std::string s) { return s + "abcd"; },
  30. [](int i) { return i + 1; },
  31. [](double f) { return f + 2; }
  32. );
  33. BOOST_HANA_RUNTIME_CHECK(f(1) == hana::just(1 + 1));
  34. BOOST_HANA_RUNTIME_CHECK(f(2.3) == hana::just(static_cast<int>(2.3) + 1));
  35. }