[英]How to static_cast between references to int and scoped enum?
我有以下枚举和输入流运算符:
enum class MsrEncryptionStatus : unsigned char
{
Unknown = 0xFF,
None = 0,
Ksn,
Dukpt,
Other
};
inline std::istream& operator>>(std::istream& s, MsrEncryptionStatus& status)
{
return s >> static_cast<unsigned&>(status);
}
由于我正在进行转换的方式,上面的operator>>
实现不会编译。 Clang抱怨说:
main.cpp:34:16: error: non-const lvalue reference to type 'unsigned int' cannot bind to a value of unrelated type 'MsrEncryptionStatus'
return s >> static_cast<unsigned&>(status);
^ ~~~~~~
我要做的是避免定义一个变量来暂时保存输入流中的值,然后再static_cast
它。 有人能帮助我理解我在这里缺少的东西吗? 我觉得我错过了一个关于static_cast
如何在lvalues上运行的基本部分,例如,感觉就像在这里创建了一个临时的,如果这是真的,我不能将它绑定到非const左值引用。
我的编译器也拒绝进行静态转换,但由于你的其他义务,临时变量无论如何都更好。
您需要读取该值,对MsrEncryptionStatus进行验证,然后将其分配给status,或者设置failbit。
这是cppreference推荐的模板
std::istream& operator>>(std::istream& is, T& obj)
{
// read obj from stream
if( /* T could not be constructed */ )
is.setstate(std::ios::failbit);
return is;
}
没有从MsrEncryptionStatus到unsigned int&的安全转换。 这就是static_cast失败的原因。 如果您完全确定自己在做什么,可以使用reinterpret_cast。
在接下来的示例中,我将向您展示reinterpret_cast的危险程度:
int main( )
{
std::ifstream i( "input.dat" ) ;
unsigned a ;
unsigned char b ;
i >> a ;
i >> reinterpret_cast<unsigned&>(b) ; // What was I thinking when I wrote this?
std::cout << a << " " << b << std::endl ;
return 0 ;
}
如果input.dat的内容是:
1234 5678
结果将是这样的:
22 .
这证明你已经覆盖了堆栈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.