std::alignment_of
来自cppreference.com
<tbody>
</tbody>
| 在标头 <type_traits> 定义
|
||
template< class T > struct alignment_of; |
(C++11 起) | |
提供成员常量 value,它等于类型 T 的对齐要求,如同用 alignof 表达式获得。若 T 是数组类型,则返回元素类型的对齐要求。若 T 是引用类型,则返回被引用类型的对齐要求。
若 alignof(T) 不是合法表达式,则行为未定义。
如果程序添加了 std::alignment_of 或 std::alignment_of_v(C++17 起) 的特化,那么行为未定义。
辅助变量模板
<tbody> </tbody> template< class T > constexpr std::size_t alignment_of_v = alignment_of<T>::value; |
(C++17 起) | |
继承自 std::integral_constant
成员常量
value [静态] |
alignof(T) (公开静态成员常量) |
成员函数
operator std::size_t |
将对象转换到 std::size_t,返回 value (公开成员函数) |
operator() (C++14) |
返回 value (公开成员函数) |
成员类型
| 类型 | 定义 |
value_type
|
std::size_t
|
type
|
std::integral_constant<std::size_t, value>
|
可能的实现
template<class T>
struct alignment_of : std::integral_constant<std::size_t, alignof(T)> {};
|
注解
此类型特征早于 alignof 关键词出现,该关键词能用于较简明地获得相同值。
示例
运行此代码
#include <cstdint>
#include <iostream>
#include <type_traits>
class A {};
struct B
{
std::int8_t p;
std::int16_t q;
};
int main()
{
std::cout << std::alignment_of<A>::value << ' ';
std::cout << std::alignment_of<B>::value << ' ';
std::cout << std::alignment_of<int>() << '\n'; // 另一种语法
std::cout << std::alignment_of_v<double> << '\n'; // c++17 另一种语法
}
可能的输出:
1 2 4 8
参阅
alignof (C++11)
|
查询类型的对齐要求 (operator) |
alignas (C++11)
|
指定该变量的存储应该按指定量对齐 (specifier) |
(C++11 起)(C++23 弃用) |
定义适于用作给定大小的类型的未初始化存储的类型 (类模板) |
(C++11 起)(C++23 弃用) |
定义适于用作所有给定类型的未初始化存储的类型 (类模板) |
(C++11) |
具有不小于任何基础类型的内存对齐需求的平凡类型 (typedef) |