class template
<memory>

std::pointer_traits

template <class Ptr> class pointer_traits;    // template
template <class T> class pointer_traits<T*>;  // template specialization
Pointer traits
This is a traits class to describe certain attributes of pointers and pointer-like classes.

The <memory> header provides both an unspecialized version (with default functionality for pointer-like classes), and a version specialized for pointer types (T*).

A pointer-like class is a class that simulates the behavior of a pointer. The unspecialized version of this template can be used for any pointer-like class that either has element_type as member type, or is a template instantiation of a class that uses the first template parameter to represent the pointed type. Additional requirements shall be met if members rebind and/or pointer_to are instantiated (see below).

If a pointer-like class lacks these requirements, this template class can still be custom specialized to provide a more specific functionality applicable to the type.

Template parameters

Ptr
Pointer-like type.
T
Pointed type.

Member types

The following aliases are member types of pointer_traits:

member typeinterpretationdefinition in unspecialized pointer_traitsdefinition in pointer_traits<T*> specialization
pointerThe pointer typeTemplate parameter PtrT*
element_typeType of pointed valueEither Ptr::element_type (if such type exists), or the first template argument used to instantiate Ptr (if Ptr is a class template instantiation).T
difference_typeType resulting from subtracting two elements of type Ptr.Ptr::difference_type (if such type exists), or std::ptrdiff_t otherwise.std::ptrdiff_t
rebind<V>Type that rebinds to VEither Ptr::rebind<V> (if such type exists), or an instantiation of the template used to instantiate Ptr, using V as first template parameter instead (if Ptr is a class template instantiation).V*
*Note: rebind is an alias template.

Member functions


Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// pointer_traits example
#include <iostream>
#include <memory>

// using pointer_traits to determine return type:
template <class T>
typename std::pointer_traits<T>::element_type dereference_pointer (T pt) {
  return *pt;
}

int main() {
  int* foo = new int(1);
  std::shared_ptr<int> bar (new int(2));

  std::cout << "foo: " << dereference_pointer (foo) << '\n';
  std::cout << "bar: " << dereference_pointer (bar) << '\n';

  delete foo;
  return 0;
}


Output:
foo: 1
bar: 2

pointer_traits