2017-04-20 62 views
0

如何static_assert 3項在編譯時是這樣的相同。最乾淨的方法static_assert oneline的3個或更多項目

union 
{ 
    std::uint32_t multibyte; 
    std::uint8_t bytes[4]; 
} test; 

static_assert(sizeof(test) == sizeof(test.multibyte) == sizeof(test.bytes), "Union size mismatch."); 

所以當然這裏的static_assert失敗,因爲最後的檢查將是1 == 4.是否存在更清潔的方式除了

static_assert(sizeof(test.bytes) == sizeof(test.multibyte) && sizeof(test) == sizeof(test.bytes), "Union size mismatch."); 

回答

1

如果你能夠使用然後通過下面的例子你可以static_assert情況下也是如此,如果他們能在constant expression使用:使用

template<typename T, typename... Ts> 
constexpr bool compare_sizes(T&&, Ts&&...) noexcept { 
    using expand = int[]; 
    bool result = sizeof...(Ts) > 0; 

    static_cast<void>(expand { 
     0, (static_cast<void>(result &= (sizeof(Ts) == sizeof(T))), 0)... 
    }); 
    return result; 
} 

例與union { /* ... */ } test

static_assert(compare_sizes(test, test.multibyte, test.bytes), "Size mismatch."); 

注意變量聲明和使用static_cast聲明中constexpr函數體中被禁止,直到

+0

是的,這將通過不同的設計修復這個例子。我正在尋找,如果有一些編譯時間std :: equal/memcmp一樣的解決方案.. – ckain

+0

@ckain,更新了我的答案。 – Akira

2

你可以寫一個結構:

template<typename...> struct AllSame; 

template<typename Arg1, typename Arg2, typename... Args> 
struct AllSame<Arg1, Arg2, Args...> 
{ 
    static constexpr bool value = sizeof(Arg1) == sizeof(Arg2) && AllSame<Arg1, Args...>::value; 
}; 

template<typename Arg> 
struct AllSame<Arg> 
{ 
     static constexpr bool value = true; 
}; 

沒有測試過,可能含有錯誤。

+0

它的工作原理是,'AllSame :: value'返回給我'true',並且可以在'static_assert'聲明中使用。 – Akira

相關問題