Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-11-03 09:44:07

0001 //------------------------------- -*- C++ -*- -------------------------------//
0002 // Copyright Celeritas contributors: see top-level COPYRIGHT file for details
0003 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
0004 //---------------------------------------------------------------------------//
0005 //! \file corecel/io/EnumStringMapper.hh
0006 //---------------------------------------------------------------------------//
0007 #pragma once
0008 
0009 #include <type_traits>
0010 
0011 #include "corecel/Assert.hh"
0012 #include "corecel/cont/Array.hh"
0013 
0014 #include "detail/EnumStringMapperImpl.hh"
0015 
0016 namespace celeritas
0017 {
0018 //---------------------------------------------------------------------------//
0019 /*!
0020  * Map enums to strings for user output.
0021  *
0022  * This should generally be a static const class.
0023  *
0024  * Example:
0025  * \code
0026     char const* to_cstring(Foo value)
0027     {
0028         static EnumStringMapper<Foo> const convert{"foo", "bar", "baz"};
0029         return convert(value);
0030     }
0031  * \endcode
0032  */
0033 template<class T>
0034 class EnumStringMapper
0035 {
0036     static_assert(std::is_enum<T>::value, "not an enum type");
0037     static_assert(static_cast<int>(T::size_) >= 0, "invalid enum type");
0038 
0039   public:
0040     //! Construct with one string per valid enum value
0041     template<class... Ts>
0042     explicit CELER_CONSTEXPR_FUNCTION EnumStringMapper(Ts... strings)
0043         : strings_{strings..., detail::g_invalid_string}
0044     {
0045         // Protect against leaving off a string
0046         static_assert(sizeof...(strings) == static_cast<size_type>(T::size_),
0047                       "All strings (except size_) must be explicitly given");
0048     }
0049 
0050     // Convert from a string
0051     inline char const* operator()(T value) const;
0052 
0053   private:
0054     using size_type = std::underlying_type_t<T>;
0055 
0056     Array<char const*, static_cast<size_type>(T::size_) + 1> const strings_;
0057 };
0058 
0059 //---------------------------------------------------------------------------//
0060 // INLINE DEFINITIONS
0061 //---------------------------------------------------------------------------//
0062 /*!
0063  * Convert an enum to the corresponding string.
0064  */
0065 template<class T>
0066 char const* EnumStringMapper<T>::operator()(T value) const
0067 {
0068     CELER_EXPECT(value <= T::size_);
0069     return strings_[static_cast<size_type>(value)];
0070 }
0071 
0072 //---------------------------------------------------------------------------//
0073 }  // namespace celeritas