Each Better Enum now has an internal enum class type to which it is convertible,
instead of being convertible to the regular enum that defines its constants.
switch statements are compiled at the enum class type. This comes at the price
of the user having to type +Enum::Constant instead of Enum::Constant in cases,
in order to trigger an explicit promotion of the pre-C++11 enum to Better Enum,
so it can then be implicitly converted to the enum class.
The remaining "hole" is that direct references to constants (Enum::Constant) are
still implicitly convertible to integral types, because they have naked
pre-C++11 enum type.
These return values of an optional type better_enums::optional<T>. This type is
defined in the spirit of boost::optional<T> and std::optional<T>, but is easy to
manipulate at compile time. Two additional macros BETTER_ENUMS_USE_OPTIONAL and
BETTER_ENUMS_EXTRA_INCLUDE are honored, whose intent is for the user to be able
to inject an alternative option type. However, there are currently no viable
alternatives. boost::optional<T> does not play well with constexpr, and I failed
to make the code compile with std::optional<T>. I did not try very hard. I
intend to support std::optional<T> in the future. Perhaps it will be the
default, when available.
A Better Enum is normally implicitly convertible to its internal enum type,
which makes it then implicitly convertible to an integer as well. The former
conversion is necessary for Better Enums to be usable in switch statements.
This change makes it possible to define BETTER_ENUMS_SAFER_SWITCH, which makes
Better Enums convert to an enum class, preventing the implicit conversion to
integers. The drawback is that switch cases have to be written as
case Enum::_Case::A:
instead of
case Enum::A:
The interface is now uniformly constexpr, including to_string and the _names
iterable. Without the weak symbol, the remaining code is also entirely standard
C++.
The compile-time string trimming code in this commit has a negative impact on
performance. The performance test is now twice as slow as including <iostream>,
whereas before it was faster. That test declares an excessive number of enums,
though, so perhaps in typical usage, and with some future optimizations, the
impact will not be so significant.
There may be other ways to solve this, such as providing a version of the macro
that does not trim strings at compile time, but only checks if they need
trimming. If some string does need trimming, that macro would fail a
static_assert and ask the user to use the slow macro.