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