default.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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/core/default.hpp>
  6. #include <boost/hana/core/tag_of.hpp>
  7. #include <algorithm>
  8. #include <iterator>
  9. #include <sstream>
  10. #include <vector>
  11. namespace hana = boost::hana;
  12. // In the header defining the concept of a Printable
  13. template <typename T>
  14. struct print_impl : hana::default_ {
  15. template <typename Stream, typename X>
  16. static void apply(Stream& out, X const& x)
  17. { out << x; }
  18. };
  19. auto print = [](auto& stream, auto const& x) {
  20. return print_impl<hana::tag_of_t<decltype(x)>>::apply(stream, x);
  21. };
  22. // In some other header
  23. template <typename T>
  24. struct print_impl<std::vector<T>> {
  25. template <typename Stream>
  26. static void apply(Stream& out, std::vector<T> const& xs) {
  27. out << '[';
  28. std::copy(begin(xs), end(xs), std::ostream_iterator<T>{out, ", "});
  29. out << ']';
  30. }
  31. };
  32. static_assert(hana::is_default<print_impl<int>>{}, "");
  33. static_assert(!hana::is_default<print_impl<std::vector<int>>>{}, "");
  34. int main() {
  35. {
  36. std::stringstream s;
  37. print(s, std::vector<int>{1, 2, 3});
  38. BOOST_HANA_RUNTIME_CHECK(s.str() == "[1, 2, 3, ]");
  39. }
  40. {
  41. std::stringstream s;
  42. print(s, "abcd");
  43. BOOST_HANA_RUNTIME_CHECK(s.str() == "abcd");
  44. }
  45. }