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

早过忘川 提交于 2019-12-23 09:39:28

问题


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:


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.)


来源:https://stackoverflow.com/questions/46256697/why-does-not-stdnullptr-t-work-with-stdcout-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!