如何在对int和作用域枚举的引用之间进行static_cast
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
如何在左值上运行的一个基本部分,例如,它感觉像是在这里创建了一个临时的,如果这是真的,我就不能将它绑定到一个非常量的左值引用。
我的编译器也拒绝进行静态转换,但由于您的其他义务,临时变量无论如何都更好。
您需要读取该值,根据MsrEncryptionStatus对其进行验证,然后将其分配给status或设置故障位。
以下是来自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。
在下一个例子中,我将向您展示represet_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 .
这证明你已经覆盖了堆栈。
相关文章:
- 在 const 函数中通过引用和指针返回之间的区别
- 返回引用实例和非引用实例(return mystr & vs mystr)之间的区别是什么?
- 使用 enable_if 在按值传递与按引用传递之间更改函数声明
- 按引用传递和按地址传递之间的差异
- 常量引用和引用之间的区别
- 按值和引用传递指针之间的区别?
- C++ 对非常量对象的常量引用和对非常量对象的非常量引用之间的区别
- 模板流运算符重载错误:引用初始化无效,与basic_istream和basic_ifstream之间的差异有关
- 当我使用按引用返回时,我不知道这些代码之间的区别
- 按引用传递和动态内存分配之间的区别是什么
- 左值引用和右值引用之间的区别
- 通过引用传递对象和基元之间的区别
- lambda 表达式中引用捕获的 constexpr 变量和非显式捕获的 constexpr 变量之间的区别
- Rcpp 中值和引用参数之间的差异
- 是否有任何好的解决方案可以解决C 中两个类之间的交叉引用
- 返回右值引用和 &&限定函数中的值之间的区别
- 是否可以通过引用将方法从类传递到全局函数或在类之间传递?
- DLL 引用之间的区别?和用途?
- C++中的变量和引用之间的区别是什么
- 本机C++类与 WinRT 组件(引用类)之间的自动映射