C++ Standard Library C++ STL Library

C++ <cstddef> - nullptr_t Type



The C++ <cstddef> nullptr_t is a type of pointer literal, nullptr. It is a distinct type that is not itself a pointer type or a pointer to member type.

Its values are null pointer constant (NULL), which when converted to a pointer type takes the proper null pointer value.

nullptr_t is not a keyword, but identifies the type of nullptr. It is generally used in overload resolution as a different type.

In the <cstddef> header file, it is defined as follows:

typedef decltype(nullptr) nullptr_t;

Example:

In the example below, a function called myfunc is overloaded with different pointer types. One of the pointer type is nullptr_t to handle null pointer argument.

#include <iostream>
#include <cstddef>
using namespace std;
 
void myfunc(int *) {
  cout<<"Pointer to integer overload.\n";
}
 
void myfunc(double *) {
  cout<<"Pointer to double overload.\n";
}

void myfunc(nullptr_t) {
  cout<<"Null pointer overload.\n";
}

int main() {
  int* num_int;
  double* num_double;
  
  myfunc(num_int);
  myfunc(num_double);
  myfunc(nullptr); //without nullptr_t type,  
  //it would be an ambiguous call 
  //myfunc(0) - ambiguous call as all three 
  //functions are candidates
  //myfunc(NULL) - ambiguous call as NULL can
  //be an integral null pointer constant  
  
  return 0;
}

The output of the above code will be:

Pointer to integer overload.
Pointer to double overload.
Null pointer overload.

❮ C++ <cstddef> Library