簡體   English   中英

如何在int和scoped枚舉的引用之間進行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如何在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM