#include <iostream>
#include <cassert>
#include <type_traits>
template<typename T> using Underlying = std::underlying_type_t<T>;
enum class ETest : int
{
Zero = 0,
One = 1,
Two = 2
};
template<typename T> auto& castEnum(T& mX) noexcept
{
// `static_cast` does not compile
// return static_cast<Underlying<T>&>(mX);
return reinterpret_cast<Underlying<T>&>(mX);
}
int main()
{
auto x(ETest::Zero);
castEnum(x) = 1;
assert(x == ETest::One);
return 0;
}
Is this code guaranteed to always work? Or is it undefined behavior?