◐ Shell
clean mode source ↗

std::pointer_traits - cppreference.com

提供: cppreference.com

<tbody> </tbody>

ヘッダ <memory> で定義

template< class Ptr > struct pointer_traits;

(1) (C++11以上)

template< class T > struct pointer_traits<T*>;

(2) (C++11以上)

pointer_traits クラステンプレートはポインタライクな型 (boost::interprocess::offset_ptr などのファンシーポインタ) のいくつかの性質にアクセスする標準的な方法を提供します。 標準のテンプレート std::allocator_traitsAllocator によって要求される様々な typedef のためのデフォルトを決定するために pointer_traits に頼っています。

1) 特殊化されていない pointer_traits は以下の型を宣言します。

メンバ型

定義
pointer Ptr
element_type 存在すれば Ptr::element_type、そうでなく Ptr がテンプレート Template<T, Args...> の実体化であれば T
difference_type 存在すれば Ptr::difference_type、そうでなければ std::ptrdiff_t

メンバエイリアステンプレート

テンプレート 定義
template <class U> using rebind 存在すれば Ptr::rebind<U>、そうでなく Ptr がテンプレート Template<T, Args...> の実体化であれば Template<U, Args...>

メンバ関数

2) 以下の型を宣言する、ポインタ型 T* に対する特殊化が提供されます。

メンバ型

定義
pointer T*
element_type T
difference_type std::ptrdiff_t

メンバエイリアステンプレート

テンプレート 定義
template< class U > using rebind U*

メンバ関数

3) ユーザ定義のファンシーポインタ型に対する特殊化は追加の静的メンバ関数を定義しても構いません。

オプショナルなメンバ関数

ファンシーポインタから生のポインタを取得します (pointer_to の逆)
(パブリック静的メンバ関数) [edit]

ノート

rebind メンバテンプレートエイリアスは、 T を指すポインタライクな型が与えられたときに、 U を指す同じポインタライクな型を取得することを可能とします。 例えば、

using another_pointer = std::pointer_traits<std::shared_ptr<int>>::rebind<double>;
static_assert(std::is_same<another_pointer, std::shared_ptr<double>>::value);

#include <memory>
#include <iostream>

template <class Ptr>
struct BlockList
{
   // メモリブロックの事前定義。
   struct block;
   
   // ポインタライクなオブジェクト Ptr s からメモリブロックへのポインタを定義します。
   // Ptr が任意の種類の T* の場合、 block_ptr_t は block* です。
   // Ptr が smart_ptr<T> の場合、 block_ptr_t は smart_ptr<block> です。
   using block_ptr_t = typename std::pointer_traits<Ptr>::template rebind<block>;
            
   struct block
   {
      std::size_t size;
      block_ptr_t next_block;
   }; 
   
   block_ptr_t free_blocks;
}; 

int main()
{
    BlockList<int*> bl1;
    // bl1.free_blocks の型は block* です。

    BlockList<std::shared_ptr<char>> bl2;
    // bl2.free_blocks の型は std::shared_ptr<block> です。
    std::cout << bl2.free_blocks.use_count() << '\n';
}

出力:

関連項目