c++ - 测试 aligned_storage 的大小

标签 c++ c++11 c++14

为了测试特定类型是否适合 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 most Len and whose alignment is a divisor of Align.

因此,任何尺寸小于或等于 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/

相关文章:

c++ - 打印一行星号

c# - 访问 PC 音频输入流

c++ - 难以理解 C++ 依赖类型,以及当前实例化的内容

c++ - 变量模板 + std::map 的通用 lambda

php - 需要帮助将 XTEA C++ 代码移植到 PHP

c++ - 段错误

C++ 右值引用转发性能

c++ - 有没有什么方法可以在没有 std::move 的情况下调用 C++ 中的移动赋值运算符?

c++ - 如何检测模板参数是否为 noexcept 函数?

c++ - 为什么参数不是常量表达式?