Why does not std::nullptr_t work with std::cout in C++?

1.3k views Asked by At

I learned about std::nullptr_t that is the type of the null pointer literal, nullptr.

Then I made small program :

#include <iostream>

int main() 
{
    std::nullptr_t n1; 
    std::cout<<n1<<endl;
    return 0;
} 

Here, nullptr_t is data type and n1 is variable and I'm trying to print the value of variable. But, Compiler give an error:

prog.cpp: In function 'int main()':
prog.cpp:6:11: error: ambiguous overload for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'std::nullptr_t')
  std::cout<<n1<<endl;

Why does not std::nullptr_t work with std::cout in C++? What am I wrong here?

1

There are 1 answers

9
cdhowie On

operator<< for output streams has overloads for multiple different types of pointers, but not std::nullptr_t 1. This means that the compiler cannot determine which overload to call, because any of the overloads accepting a pointer are equally good. (For example, it accepts char const * for C-style strings, and also void const *, which will output the raw pointer value.)

One option to fix this would be to define your own overload that forces the use of the void const * overload:

std::ostream & operator<<(std::ostream &s, std::nullptr_t) {
    return s << static_cast<void *>(nullptr);
}

Or have it do something else:

std::ostream & operator<<(std::ostream &s, std::nullptr_t) {
    return s << "nullptr";
}

Notes:

  • 1 As pointed out in the comments, there is an overload accepting std::nullptr_t in C++17, so this will cease to be an issue if you are using a conforming C++17 implementation.
  • endl needs std::-qualification -- but you should use '\n' here anyway. (std::endl is only a good idea when you need the stream flushed.)