为了测试特定类型是否适合 aligned_storage
,我创建了以下测试结构:
template< typename T, std::size_t Bytes >
struct fits_in_storage : public std::integral_constant<bool, sizeof(std::aligned_storage<Bytes>::type) >= sizeof(std::aligned_storage<sizeof(T)>::type)>
{};
现在我有点想知道这样的测试是否会出现在 stdlib 中。 不愿重新发明轮子。
我正在使用它来检查 header 定义的 aligned_storage
(大小为 Bytes
)是否可以采用内部数据类型,该类型仅在实际编译单元中可用。
最佳答案
无法保证 aligned_storage<Len, Align>::type
的大小除了它至少 Len
字节。 ::type
有可能(但不太可能)对于较小的 Len
大于更大的 Len
.
[meta.trans.other] 状态,对于
aligned_storage<std::size_t Len, std::size_t Align =
default-alignment>
The value of default-alignment shall be the most stringent alignment requirement for any C++ object type whose size is no greater than
Len
(3.9). The member typedef type shall be a POD type suitable for use as uninitialized storage for any object whose size is at mostLen
and whose alignment is a divisor ofAlign
.
因此,任何尺寸小于或等于 Len
的对象可以存储在 aligned_storage<Len>::type
中.因此,您的支票可以简化为:
template< typename T, std::size_t Bytes >
struct fits_in_storage
: public std::integral_constant<bool, (Bytes >= sizeof(T))>
{};
当然可以简化为Bytes >= sizeof(T)
.
关于c++ - 测试 aligned_storage 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19095272/