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?
operator<<
for output streams has overloads for multiple different types of pointers, but notstd::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 acceptschar const *
for C-style strings, and alsovoid 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:Or have it do something else:
Notes:
std::nullptr_t
in C++17, so this will cease to be an issue if you are using a conforming C++17 implementation.endl
needsstd::
-qualification -- but you should use'\n'
here anyway. (std::endl
is only a good idea when you need the stream flushed.)