安全而可维护的将整数转换为枚举类的方法
创始人
2024-11-04 19:00:42
0

为了确保将整数转换为枚举类的安全和可维护性,我们应该使用C++17及更高版本中的std::from_chars函数,并结合static_assert检查是否存在枚举值与整数值的匹配,以避免枚举意外添加或删除项目时的错误。

示例代码如下:

#include #include

enum class Color { Red = 1, Green = 2, Blue = 3 };

template constexpr bool is_enum_class_v = std::is_enum_v && !std::is_convertible_v;

template constexpr T to_enum(int value) { static_assert(is_enum_class_v, "T must be an enum class type");

T result;
if (auto [ptr, ec] = std::from_chars(std::to_string(value).c_str(), std::to_string(value).c_str() + std::to_string(value).size(), reinterpret_cast::type&>(result)); ec == std::errc())
    return result;

throw std::invalid_argument("Value cannot be converted to enum class");

}

int main() { int value = 2;

Color color = to_enum(value);

std::cout << static_cast(color) << std::endl;

return 0;

}

相关内容

热门资讯

目前!hhpoker有作必弊的... 目前!hhpoker有作必弊的吗,潮汕馆辅助,一直是有辅助工具(哔哩哔哩)1、下载好潮汕馆辅助脚本下...
截至目前!wepoker透视底... 截至目前!wepoker透视底牌脚本,凑一桌游戏免费辅助器,好像真的有辅助技巧(哔哩哔哩)凑一桌游戏...
日前!wepoker作必弊视频... 日前!wepoker作必弊视频,潮汕暗宝辅助器,切实是真的有辅助工具(哔哩哔哩)1.潮汕暗宝辅助器 ...
此事引发广泛关注!hhpoke... 此事引发广泛关注!hhpoker是内部控制吗,打哈儿麻将辅助下载,切实有辅助app(哔哩哔哩)1、每...
据权威媒体报道!hhpoker... 据权威媒体报道!hhpoker辅助挂下载,九游破解辅助插件,本来真的是有辅助工具(哔哩哔哩)1、每一...
网友热议!wepoker透视脚... 网友热议!wepoker透视脚本免费,约局吧辅助辅助外开挂,本来是真的有辅助方法(哔哩哔哩)1、约局...
据玩家消息!wepoker透视... 据玩家消息!wepoker透视脚本免费,禅游指尖四川作必弊,一直存在有辅助教程(哔哩哔哩)禅游指尖四...
记者获悉!hhpkoer辅助器... 记者获悉!hhpkoer辅助器,wepoker辅助软件视频,切实存在有辅助软件(哔哩哔哩)1、每一步...
近日!德州透视是真的假的,哥哥... 近日!德州透视是真的假的,哥哥打大a辅助,总是真的有辅助神器(哔哩哔哩)1、起透看视 德州透视是真的...
今日!hhpoker破解工具,... 今日!hhpoker破解工具,潮汕汇app辅助,其实有辅助方法(哔哩哔哩)1、实时潮汕汇app辅助透...