template <class Ptr> class pointer_traits; // templatetemplate <class T> class pointer_traits<T*>; // template specialization
| member type | interpretation | definition in unspecialized pointer_traits | definition in pointer_traits<T*> specialization |
|---|---|---|---|
| pointer | The pointer type | Template parameter Ptr | T* |
| element_type | Type of pointed value | Either 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_type | Type 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 V | Either 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* |
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;
}
foo: 1 bar: 2