2017-04-20 59 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

相关问题