在线文档教程
C++
应用 | Utilities

std::pointer_traits

STD::指针[医]性状

Defined in header
template< class Ptr > struct pointer_traits;(1)(since C++11)
template< class T > struct pointer_traits<T*>;(2)(since C++11)

pointer_traits类模板提供了访问类指针类型%28的某些属性的标准化方法。花哨指针,如*进程间::抵消[医]PTR29%。标准模板std::allocator_traits倚靠pointer_traits来确定各种类型的默认值。Allocator...

1%29非专业pointer_traits声明以下类型:

成员类型

TypeDefinition
pointerPtr
element_typePtr::element_type if present. Otherwise T if Ptr is a template instantiation Template<T, Args...>
difference_typePtr::difference_type if present, otherwise std::ptrdiff_t

成员别名模板

TemplateDefinition
template <class U> using rebindPtr::rebind<U> if exists, otherwise Template<U, Args...> if Ptr is a template instantiation Template<T, Args...>

成员函数

pointer_to staticobtains a dereferenceable pointer to its argument (public static member function)

2%29为指针类型提供专门化,T*,它声明了以下类型。

成员类型

TypeDefinition
pointerT*
element_typeT
difference_typestd::ptrdiff_t

成员别名模板

TemplateDefinition
template< class U > using rebindU*

成员函数

pointer_to staticobtains a dereferenceable pointer to its argument (public static member function)

注记

重新绑定成员模板别名使得在指针类类型指向T的情况下,可以获得指向U的相同的指针类型--例如,

二次

typedef std::pointer_traits<std::shared_ptr<int>>::rebind<double> another_pointer; static_assert(std::is_same<another_pointer, std::shared_ptr<double>>::value, ""

二次

二次

#include <memory> #include <iostream> template <class Ptr> struct BlockList { // Predefine a memory block struct block; // Define a pointer to a memory block from the kind of pointer Ptr s // If Ptr is any kind of T*, block_ptr_t is block* // If Ptr is smart_ptr<T>, block_ptr_t is smart_ptr<block> typedef typename std::pointer_traits<Ptr>::template rebind<block> block_ptr_t; struct block { std::size_t size; block_ptr_t next_block; }; block_ptr_t free_blocks; }; int main() { BlockList<int*> bl1; // The type of bl1.free_blocks is block* BlockList<std::shared_ptr<char>> bl2; // The type of bl2.free_blocks is std::shared_ptr<block> std::cout << bl2.free_blocks.use_count() << '\n'; }

二次

产出:

二次

​0​

二次

另见

allocator_traits (C++11)provides information about allocator types (class template)
addressof (C++11)obtains actual address of an object, even if the & operator is overloaded (function template)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/Memory/指针[医]性状