What are the uses of the type `std::nullptr_t`?

Hindol picture Hindol · Aug 22, 2012 · Viewed 7.3k times · Source

I learned that nullptr, in addition to being convertible to any pointer type (but not to any integral type) also has its own type std::nullptr_t. So it is possible to have a method overload that accepts std::nullptr_t.

Exactly why is such an overload required?

Answer

torrey.lyons picture torrey.lyons · Aug 22, 2012

If more than one overload accepts a pointer type, an overload for std::nullptr_t is necessary to accept a nullptr argument. Without the std::nullptr_t overload, it would be ambiguous which pointer overload should be selected when passed nullptr.

Example:

void f(int *intp)
{
    // Passed an int pointer
}

void f(char *charp)
{
    // Passed a char pointer
}

void f(std::nullptr_t nullp)
{
    // Passed a null pointer
}