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