|
||||
File indexing completed on 2025-01-18 09:54:48
0001 //----------------------------------*-C++-*----------------------------------// 0002 // Copyright 2024 UT-Battelle, LLC, and other Celeritas developers. 0003 // See the top-level COPYRIGHT file for details. 0004 // SPDX-License-Identifier: (Apache-2.0 OR MIT) 0005 //---------------------------------------------------------------------------// 0006 //! \file corecel/io/StreamableVariant.hh 0007 //---------------------------------------------------------------------------// 0008 #pragma once 0009 0010 #include <ostream> 0011 #include <sstream> 0012 #include <variant> 0013 0014 #include "corecel/Assert.hh" 0015 0016 namespace celeritas 0017 { 0018 //---------------------------------------------------------------------------// 0019 /*! 0020 * Helper class to print a variant to a stream. 0021 * 0022 * Example: 0023 * \code 0024 std::cout << StreamableVariant{surface} << std::endl; 0025 \endcode 0026 */ 0027 template<class T> 0028 struct StreamableVariant 0029 { 0030 T value; 0031 }; 0032 0033 //---------------------------------------------------------------------------// 0034 // Deduction guide 0035 template<class T> 0036 StreamableVariant(T&&) -> StreamableVariant<T>; 0037 0038 //---------------------------------------------------------------------------// 0039 // IMPLEMENTATION 0040 //---------------------------------------------------------------------------// 0041 namespace detail 0042 { 0043 struct GenericToStream 0044 { 0045 std::ostream& os; 0046 0047 template<class T> 0048 void operator()(T&& obj) const 0049 { 0050 this->os << obj; 0051 } 0052 }; 0053 } // namespace detail 0054 0055 //---------------------------------------------------------------------------// 0056 // FREE FUNCTIONS 0057 //---------------------------------------------------------------------------// 0058 /*! 0059 * Write a variant object's value to a stream. 0060 */ 0061 template<class T> 0062 std::ostream& operator<<(std::ostream& os, StreamableVariant<T> const& svar) 0063 { 0064 CELER_ASSUME(!svar.value.valueless_by_exception()); 0065 std::visit(detail::GenericToStream{os}, svar.value); 0066 return os; 0067 } 0068 0069 //---------------------------------------------------------------------------// 0070 /*! 0071 * Save a variant object's value to a string. 0072 */ 0073 template<class T> 0074 std::string to_string(StreamableVariant<T> const& svar) 0075 { 0076 std::ostringstream os; 0077 os << svar; 0078 return os.str(); 0079 } 0080 0081 //---------------------------------------------------------------------------// 0082 } // namespace celeritas
[ Source navigation ] | [ Diff markup ] | [ Identifier search ] | [ general search ] |
This page was automatically generated by the 2.3.7 LXR engine. The LXR team |