当 static_cast-ing 值超出枚举类集时如何引发错误/警告
考虑我必须将 int
类型转换为 enum
的情况。当使用 static_cast
执行此操作时,风险在于,即使超出枚举允许值的值也会被强制转换。以以下代码为例:
#include<iostream>
int main(char argc, char* argv[])
{
enum class EnumType : uint8_t
{
A = 0,
B = 1,
default=255
};
EnumType enum_var;
uint8_t num_var_out_of_range = 31;
enum_var = static_cast<EnumType>(num_var_out_of_range);
std::cout<<static_cast<int>(enum_var)<<std::endl;
return 0;
}
31
不在枚举值集中。我猜想强制转换是有效的,因为枚举的基础类型能够表示该值,但在我看来,在这种情况下提出错误或警告更合适。有没有办法管理此类案件?
Consider the case where I have to convert an int
type to an enum
. When doing this with static_cast
the risk is that even values out of admissible values of the enum are casted. Take as example the following code:
#include<iostream>
int main(char argc, char* argv[])
{
enum class EnumType : uint8_t
{
A = 0,
B = 1,
default=255
};
EnumType enum_var;
uint8_t num_var_out_of_range = 31;
enum_var = static_cast<EnumType>(num_var_out_of_range);
std::cout<<static_cast<int>(enum_var)<<std::endl;
return 0;
}
31
is not in the set of the enum values. I guess that the cast is valid because the underlying type of the enum is able to represent that value, but in my opinion it would more appropriate to raise an error or warning in this case. Is there a way to manage such cases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论