如何使static_assert 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.");发布于 2017-04-27 10:13:05
您可以为此编写一个结构:
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;
};没有测试,可能包含错误。
发布于 2017-04-24 07:53:11
如果您能够使用c++14,那么通过下面的示例,您也可以使用static_assert实例,如果它们可以在常量表达式中使用
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函数体中是禁止的,直到c++14。
https://stackoverflow.com/questions/43520544
复制相似问题