std::add_pointer (3) - Linux Manuals

std::add_pointer: std::add_pointer


std::add_pointer - std::add_pointer


Defined in header <type_traits>
template< class T > (since C++11)
struct add_pointer;

If T is a reference type, then provides the member typedef type which is a pointer to the referred type.
Otherwise, if T names an object type, a function type that is not cv- or ref-qualified, or a (possibly cv-qualified) void type, provides the member typedef type which is the type T*.
Otherwise (if T is a cv- or ref-qualified function type), provides the member typedef type which is the type T.

Member types

Name Definition
type pointer to T or to the type referenced by T

Helper types

template< class T > (since C++14)
using add_pointer_t = typename add_pointer<T>::type;

Possible implementation

  namespace detail {

  template <class T>
  struct type_identity { using type = T; }; // or use std::type_identity (since C++20)

  template <class T>
  auto try_add_pointer(int) -> type_identity<typename std::remove_reference<T>::type*>;
  template <class T>
  auto try_add_pointer(...) -> type_identity<T>;

  } // namespace detail

  template <class T>
  struct add_pointer : decltype(detail::try_add_pointer<T>(0)) {};


// Run this code

  #include <iostream>
  #include <type_traits>

  int main()
      int i = 123;
      int& ri = i;
      typedef std::add_pointer<decltype(i)>::type IntPtr;
      typedef std::add_pointer<decltype(ri)>::type IntPtr2;
      IntPtr pi = &i;
      std::cout << "i = " << i << "\n";
      std::cout << "*pi = " << *pi << "\n";

      static_assert(std::is_pointer<IntPtr>::value, "IntPtr should be a pointer");
      static_assert(std::is_same<IntPtr, int*>::value, "IntPtr should be a pointer to int");
      static_assert(std::is_same<IntPtr2, IntPtr>::value, "IntPtr2 should be equal to IntPtr");

      typedef std::remove_pointer<IntPtr>::type IntAgain;
      IntAgain j = i;
      std::cout << "j = " << j << "\n";

      static_assert(!std::is_pointer<IntAgain>::value, "IntAgain should not be a pointer");
      static_assert(std::is_same<IntAgain, int>::value, "IntAgain should be equal to int");


  i = 123
  *pi = 123
  j = 123

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG_2101 C++11 std::add_pointer was required to produce Produces cv-/ref-qualified function types themselves.
                    pointer to cv-/ref-qualified function types.

See also

is_pointer checks if a type is a pointer type
               (class template)

remove_pointer removes a pointer from the given type
               (class template)