Why doesn't std :: nullptr_t work with std :: cout in C ++?

I found out about std::nullptr_t , which is a type of null pointer literal, nullptr .

Then I made a small program:

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

Here nullptr_t is the data type and n1 is the variable, and I'm trying to print the value of the variable. But, the compiler throws 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 std::nullptr_t work with std::cout in C ++? What am I wrong here?

+5
source share
1 answer

operator<< for output streams has overloads for several different types of pointers, but not std::nullptr_t 1 . This means that the compiler cannot determine which overload needs to be called, because any of the overloads that take a pointer are equally good. (For example, it takes char const * for C-style strings, as well as void const * , which prints the value of a raw pointer.)

One option to fix this is to define your own overload, which forces you to use the void const * overload:

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

Or do something else:

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

Notes:

  • 1 As stated in the comments, in C ++ 17 there is an overload that takes std::nullptr_t , so this will no longer be a problem if you use the appropriate C ++ 17 implementation.
  • endl requires std:: -qualification - but you should still use '\n' . ( std::endl is only a good idea when you need a thread flushed.)
+7
source

Source: https://habr.com/ru/post/1271878/


All Articles