2013-05-16 34 views
0

已引用此問題:Can an enum class be converted to the underlying type?InterlockedCompareExchange16(帶有VS2012)的C++短枚舉問題

在我的代碼有有效:

enum class STATE : short 
{ 
    EMPTY, 
    PRESENT, 
    PARTIAL, 
}; 

volatile STATE state; 

然後我寫了typedefstatic_assert

typedef volatile std::underlying_type<STATE> state_type; 
static_assert (sizeof (state_type) == sizeof (short), "Error - unsafe for use with InterlockedCompareExchange16"); 

最後,我試圖與InterlockedCompareExchange16設置狀態:

if (InterlockedCompareExchange16 (static_cast<state_type *>(&state), STATE::PRESENT, STATE::EMPTY) == STATE::EMPTY) 
{ 
} 

我從VS2012中收到以下錯誤:

  1. static_assert失敗抱怨state_type不是大小short

  2. static_cast同樣抱怨說,它不能從volatile STATE *轉換爲state_type *

請任何人都可以給我任何指針如何最好地解決我的代碼?

+0

請不要修改問題以回答問題。對於後來出現問題的人來說,這會讓人感到困惑,並使得答案變得多餘。回滾。 – hmjd

+0

只是爲了承認我的失敗,之前提到的錯誤是錯誤地使用'underlying_type',但我仍然得到'static_cast'抱怨。 –

+0

對不起@hmjd。我剛剛添加了解釋性評論 - 這足夠嗎? –

回答

2

std::underlying_type

Defines a member typedef type of type that is the underlying type for the enumeration T.

更改爲:

typedef typename std::underlying_type<STATE>::type state_type; 
              //^^^^ 

一種強烈的動機類型enum class是防止轉化爲int,因此試圖強制轉換爲基本類型的衝突與預期使用enum s(見Strongly Typed Enums (revision 3))。

而不是使用OS特定線程機制的使用std::atomic<>模板加入到C++ 11:

std::atomic<STATE> state(STATE::EMPTY); 
STATE expected(STATE::EMPTY); 
if (state.compare_exchange_strong(expected, STATE::PRESENT)) 
{ 
    // 'state' set to 'PRESENT'. 
} 

這消除了對需求和static_assert不需要任何鑄造。

+0

謝謝 - 是的,我只是發現自己的錯誤。這解決了一個錯誤 - 我仍然得到'static_cast'抱怨。我會更新這個問題。 –

+0

不幸的是,Microsoft編譯器給出了錯誤:C2664:'_InterlockedCompareExchange16':如果我不執行任何強制轉換,則無法將參數1從'volatile STATE *'轉換爲'volatile SHORT *'。 –

+0

我認爲我的核心問題是std :: underlying_type的使用不正確。我是否應該關閉這個問題,因爲這不太可能使其他人受益。 –