introspection.sfinae.cpp 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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.hpp>
  5. #include <string>
  6. #include <vector>
  7. namespace hana = boost::hana;
  8. struct yes { std::string toString() const { return "yes"; } };
  9. struct no { };
  10. //! [optionalToString.sfinae]
  11. template <typename T>
  12. std::string optionalToString(T const& obj) {
  13. auto maybe_toString = hana::sfinae([](auto&& x) -> decltype(x.toString()) {
  14. return x.toString();
  15. });
  16. return maybe_toString(obj).value_or("toString not defined");
  17. }
  18. //! [optionalToString.sfinae]
  19. int main() {
  20. BOOST_HANA_RUNTIME_CHECK(optionalToString(yes{}) == "yes");
  21. BOOST_HANA_RUNTIME_CHECK(optionalToString(no{}) == "toString not defined");
  22. {
  23. //! [maybe_add]
  24. auto maybe_add = hana::sfinae([](auto x, auto y) -> decltype(x + y) {
  25. return x + y;
  26. });
  27. maybe_add(1, 2); // hana::just(3)
  28. std::vector<int> v;
  29. maybe_add(v, "foobar"); // hana::nothing
  30. //! [maybe_add]
  31. }
  32. }