首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::pointer_traits

Defined in header <memory>

?

?

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声明以下类型:

成员类型

Type

Definition

pointer

Ptr

element_type

Ptr::element_type if present. Otherwise T if Ptr is a template instantiation Template<T, Args...>

difference_type

Ptr::difference_type if present, otherwise std::ptrdiff_t

成员别名模板

Template

Definition

template <class U> using rebind

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

成员函数

pointer_to static

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

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

成员类型

Type

Definition

pointer

T*

element_type

T

difference_type

std::ptrdiff_t

成员别名模板

Template

Definition

template< class U > using rebind

U*

成员函数

pointer_to static

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

注记

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

二次

代码语言:javascript
复制
typedef std::pointer_traits<std::shared_ptr<int>>::rebind<double> another_pointer;
static_assert(std::is_same<another_pointer, std::shared_ptr<double>>::value, "");

二次

二次

代码语言:javascript
复制
#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';
}

二次

产出:

二次

代码语言:javascript
复制
?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)

代码语言:txt
复制
 ? cppreference.com

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

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com