From e668c099ce650dba28815ae78fdd4eaa262a8396 Mon Sep 17 00:00:00 2001 From: Peter Dimov Date: Wed, 15 Sep 2021 02:51:11 +0300 Subject: [PATCH] Add operator<< for variant --- include/boost/variant2/variant.hpp | 25 +++++++++++++++++++++ test/Jamfile | 2 ++ test/variant_ostream_insert.cpp | 36 ++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 test/variant_ostream_insert.cpp diff --git a/include/boost/variant2/variant.hpp b/include/boost/variant2/variant.hpp index 239e43f..c49fbb6 100644 --- a/include/boost/variant2/variant.hpp +++ b/include/boost/variant2/variant.hpp @@ -25,6 +25,7 @@ #include #include // std::hash #include +#include // @@ -2236,6 +2237,30 @@ template constexpr auto visit_by detail::visit_by_index_L{ std::forward(v), std::tuple( std::forward(f)... ) } ); } +// output streaming + +namespace detail +{ + +template struct ostream_insert_L +{ + std::basic_ostream& os; + variant const& v; + + template std::basic_ostream& operator()( I ) const + { + return os << unsafe_get( v ); + } +}; + +} // namespace detail + +template std::basic_ostream& operator<<( std::basic_ostream& os, variant const& v ) +{ + return mp11::mp_with_index( v.index(), + detail::ostream_insert_L{ os, v } ); +} + // hashing support namespace detail diff --git a/test/Jamfile b/test/Jamfile index f62221c..0cc5dd2 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -123,3 +123,5 @@ run variant_visit_r.cpp : : : compile variant_derived_construct.cpp ; run variant_visit_by_index.cpp ; + +run variant_ostream_insert.cpp ; diff --git a/test/variant_ostream_insert.cpp b/test/variant_ostream_insert.cpp new file mode 100644 index 0000000..34fda07 --- /dev/null +++ b/test/variant_ostream_insert.cpp @@ -0,0 +1,36 @@ +// Copyright 2021 Peter Dimov +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +#include +#include +#include +#include + +using namespace boost::variant2; + +template std::string to_string( T const& t ) +{ + std::ostringstream os; + + os << t; + + return os.str(); +} + +int main() +{ + variant v( 1 ); + + BOOST_TEST_EQ( to_string( v ), to_string( 1 ) ); + + v = 3.14f; + + BOOST_TEST_EQ( to_string( v ), to_string( 3.14f ) ); + + v = "test"; + + BOOST_TEST_EQ( to_string( v ), to_string( "test" ) ); + + return boost::report_errors(); +}