1//// 2Copyright 2005, 2006 Ion Gaztañaga 3Copyright 2005, 2006, 2017 Peter Dimov 4 5Distributed under the Boost Software License, Version 1.0. 6 7See accompanying file LICENSE_1_0.txt or copy at 8http://www.boost.org/LICENSE_1_0.txt 9//// 10 11[#pointer_to_other] 12# pointer_to_other 13:toc: 14:toc-title: 15:idprefix: pointer_to_other_ 16 17## Description 18 19The `pointer_to_other` utility provides a way, given a source pointer type, to obtain a pointer of the same type 20to another pointee type. 21 22There is test/example code in link:../../test/pointer_to_other_test.cpp[pointer_to_other_test.cpp]. 23 24## Rationale 25 26When building pointer independent classes, like memory managers, allocators, or containers, there is often a need to 27define pointers generically, so that if a template parameter represents a pointer (for example, a raw or smart pointer 28to an `int`), we can define another pointer of the same type to another pointee (a raw or smart pointer to a `float`.) 29 30``` 31template <class IntPtr> class FloatPointerHolder 32{ 33 // Let's define a pointer to a float 34 35 typedef typename boost::pointer_to_other 36 <IntPtr, float>::type float_ptr_t; 37 38 float_ptr_t float_ptr; 39}; 40``` 41 42## Synopsis 43 44`pointer_to_other` is defined in `<boost/smart_ptr/pointer_to_other.hpp>`. 45 46``` 47namespace boost { 48 49 template<class T, class U> struct pointer_to_other; 50 51 template<class T, class U, 52 template <class> class Sp> 53 struct pointer_to_other< Sp<T>, U > 54 { 55 typedef Sp<U> type; 56 }; 57 58 template<class T, class T2, class U, 59 template <class, class> class Sp> 60 struct pointer_to_other< Sp<T, T2>, U > 61 { 62 typedef Sp<U, T2> type; 63 }; 64 65 template<class T, class T2, class T3, class U, 66 template <class, class, class> class Sp> 67 struct pointer_to_other< Sp<T, T2, T3>, U > 68 { 69 typedef Sp<U, T2, T3> type; 70 }; 71 72 template<class T, class U> 73 struct pointer_to_other< T*, U > 74 { 75 typedef U* type; 76 }; 77} 78``` 79 80If these definitions are not correct for a specific smart pointer, we can define a specialization of `pointer_to_other`. 81 82## Example 83 84``` 85// Let's define a memory allocator that can 86// work with raw and smart pointers 87 88#include <boost/pointer_to_other.hpp> 89 90template <class VoidPtr> 91class memory_allocator 92{ 93 // Predefine a memory_block 94 95 struct block; 96 97 // Define a pointer to a memory_block from a void pointer 98 // If VoidPtr is void *, block_ptr_t is block* 99 // If VoidPtr is smart_ptr<void>, block_ptr_t is smart_ptr<block> 100 101 typedef typename boost::pointer_to_other 102 <VoidPtr, block>::type block_ptr_t; 103 104 struct block 105 { 106 std::size_t size; 107 block_ptr_t next_block; 108 }; 109 110 block_ptr_t free_blocks; 111}; 112``` 113 114As we can see, using `pointer_to_other` we can create pointer independent code. 115