Namespaces
Variants

std:: alignment_of

From cppreference.net
Metaprogramming library
Type traits
Type categories
(C++11)
(C++11) ( DR* )
Type properties
(C++11)
(C++11)
(C++14)
(C++11) (deprecated in C++26)
(C++11) ( until C++20* )
(C++11) (deprecated in C++20)
(C++11)
Type trait constants
Metafunctions
(C++17)
Supported operations
Relationships and property queries
(C++11)
alignment_of
(C++11)
(C++11)
(C++11)
Type modifications
Type transformations
(C++11) (deprecated in C++23)
(C++11) (deprecated in C++23)
(C++11)
(C++11) ( until C++20* ) (C++17)

Compile-time rational arithmetic
Compile-time integer sequences
定义于头文件 <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 起) 添加特化,则行为未定义。

目录

辅助变量模板

template < class T >
constexpr std:: size_t alignment_of_v = alignment_of < T > :: value ;
(C++17 起)

继承自 std:: integral_constant

成员常量

value
[static]
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>
struct 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>() << ' '; // 替代语法
    std::cout << std::alignment_of_v<double> << '\n'; // C++17 替代语法
}

可能的输出:

1 2 4 8

参见

alignof (C++11) 查询类型的对齐要求
(运算符)
alignas (C++11) 指定变量的存储应按特定量对齐
(说明符)
(since C++11) (deprecated in C++23)
定义适合用作给定大小类型的未初始化存储的类型
(类模板)
(since C++11) (deprecated in C++23)
定义适合用作所有给定类型的未初始化存储的类型
(类模板)
对齐要求与任何其他标量类型一样大的平凡类型
(类型定义)