可以使用一个函数模板来避免这种重复的复制粘贴。该函数模板可以接收一个枚举类,并使用static_cast将其转换为其底层类型。这样,每次需要将枚举类转换为其底层类型时,都可以使用该函数模板。
代码示例:
template
constexpr auto enum_to_underlying(Enum e) noexcept
{
return static_cast>(e);
}
// example usage
enum class Color { RED, GREEN, BLUE };
auto red_value = enum_to_underlying(Color::RED); // returns 0
auto green_value = enum_to_underlying(Color::GREEN); // returns 1
auto blue_value = enum_to_underlying(Color::BLUE); // returns 2
下一篇:避免重复攻击