为什么 std::nullptr_t 不能与 std::cout 一起使用C++?
Why does not std::nullptr_t work with std::cout in C++?
我了解了std::nullptr_t
这是空指针文字的类型,nullptr
.
然后我做了小程序:
#include <iostream>
int main()
{
std::nullptr_t n1;
std::cout<<n1<<endl;
return 0;
}
在这里,nullptr_t
是数据类型,n1
是变量,我正在尝试打印变量的值。但是,编译器给出一个错误:
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;
为什么std::nullptr_t
不与C++中的std::cout
一起使用?我在这里错了什么?
输出流的operator<<
对多种不同类型的指针具有重载,但不是std::nullptr_t
1。这意味着编译器无法确定要调用哪个重载,因为接受指针的任何重载都同样好。(例如,它接受 C 样式字符串的char const *
,也接受void const *
,这将输出原始指针值。
解决此问题的一种选择是定义自己的重载,强制使用void const *
重载:
std::ostream & operator<<(std::ostream &s, std::nullptr_t) {
return s << static_cast<void *>(nullptr);
}
或者让它做其他事情:
std::ostream & operator<<(std::ostream &s, std::nullptr_t) {
return s << "nullptr";
}
笔记:
- 1正如评论中指出的,C++17 中存在接受
std::nullptr_t
的重载,因此如果您使用的是符合标准的 C++17 实现,这将不再是问题。 endl
需要std::
限定 - 但无论如何你应该在这里使用'n'
。 (仅当您需要刷新流时,std::endl
才是一个好主意。
相关文章:
- 将fold表达式与std::一起用于两个元组
- 将 std::allocate_shared 与多态资源分配器一起使用
- 将 std::set 与基于键的比较器一起使用
- 如何将AERT_Allocate与 std:vector 一起使用
- 将用户定义的类型与 std::vector 和 std::sort 一起使用
- 将图形属性与 std::unique_ptr 捆绑在一起
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- 将新放置与 std::函数一起使用不起作用
- 不能将C++的"std::filesystem"库与介子构建一起使用
- 将 std::function 与模板一起使用
- 是否可以将 std::basic_ifstream 和 std::basic_ofstream 与自定义缓冲区一起使用?
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 如何将 std::find() 与 2d std: 数组一起使用?
- boost::interprocess::file_lock 与 std::ostream 一起使用时的错误行为
- std::remove() 按预期处理文字,但不能与取消引用的迭代器一起工作
- 将 std::transform 与 std::back_inserter 一起使用是否有效?
- 为什么使用与父级声明的 std::function 在与子级一起使用时会显示错误?
- 是否已经有一个 constexpr std::bit_cast 与 g++ 一起使用
- 将 std::variant 与 gmock 1.8 对象一起使用时编译错误
- 我不能将 'fill' std::vector 构造函数与 unique_ptrs 一起使用