forked from celeritas-project/celeritas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EnumStringMapper.hh
74 lines (64 loc) · 2.29 KB
/
EnumStringMapper.hh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//----------------------------------*-C++-*----------------------------------//
// Copyright 2023-2024 UT-Battelle, LLC, and other Celeritas developers.
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
//---------------------------------------------------------------------------//
//! \file corecel/io/EnumStringMapper.hh
//---------------------------------------------------------------------------//
#pragma once
#include <type_traits>
#include "corecel/Assert.hh"
#include "corecel/cont/Array.hh"
#include "detail/EnumStringMapperImpl.hh"
namespace celeritas
{
//---------------------------------------------------------------------------//
/*!
* Map enums to strings for user output.
*
* This should generally be a static const class.
*
* Example:
* \code
char const* to_cstring(Foo value)
{
static EnumStringMapper<Foo> const convert{"foo", "bar", "baz"};
return convert(value);
}
* \endcode
*/
template<class T>
class EnumStringMapper
{
static_assert(std::is_enum<T>::value, "not an enum type");
static_assert(static_cast<int>(T::size_) >= 0, "invalid enum type");
public:
//! Construct with one string per valid enum value
template<class... Ts>
explicit CELER_CONSTEXPR_FUNCTION EnumStringMapper(Ts... strings)
: strings_{strings..., detail::g_invalid_string}
{
// Protect against leaving off a string
static_assert(sizeof...(strings) == static_cast<size_type>(T::size_),
"All strings (except size_) must be explicitly given");
}
// Convert from a string
inline char const* operator()(T value) const;
private:
using size_type = std::underlying_type_t<T>;
Array<char const*, static_cast<size_type>(T::size_) + 1> const strings_;
};
//---------------------------------------------------------------------------//
// INLINE DEFINITIONS
//---------------------------------------------------------------------------//
/*!
* Convert an enum to the corresponding string.
*/
template<class T>
char const* EnumStringMapper<T>::operator()(T value) const
{
CELER_EXPECT(value <= T::size_);
return strings_[static_cast<size_type>(value)];
}
//---------------------------------------------------------------------------//
} // namespace celeritas