无法在屏幕上打印 nullptr 的值

Unable to print the value of nullptr on screen

本文关键字:打印 nullptr 的值 屏幕      更新时间:2023-10-16

我正在阅读有关nullptr的信息,并在g++和VS2010上进行锻炼。

当我这样做时

#include <iostream>
using namespace std;
auto main(void)->int
{
    int j{};    
    int* q{};   
    cout << "Value of j: " << j << endl; // prints 0
    cout << nullptr << endl;
    cout << "Value of q: " << q << endl; // prints 0
    return 0;
}

在屏幕上打印nullptr的值,g++ 和 VS 给出了编译器错误。不允许在屏幕上打印nullptr的值吗?

指针文字是关键字 nullptr。它是 std::nullptr_t 类型的 prvalue。

类型 nullptr_t 应该可以转换为 T* ,但编译器没有nullptr_t operator <<,并且不知道要nullptr转换为哪种类型。

你可以使用这个

cout << static_cast<void*>(nullptr) << endl;

这是因为nullptr的类型是 std::nullptr_t ,它没有为std::cout定义适当的运算符来打印该类型的对象。您可以像这样自己定义运算符:

//std::cout is of type std::ostream, and nullptr is of type std::nullptr_t
std::ostream& operator << (std::ostream& os, std::nullptr_t ptr)
{
    return os << "nullptr"; //whatever you want nullptr to show up as in the console
}

定义此函数后,它将用于处理通过ostream打印nullptr的所有尝试。这样,您就不需要每次打印时都投射nullptr

我在

编写一些类型参数化的测试代码(使用模板)时遇到了这个问题。我需要打印一个类型 T 的值,其中 nullptr_tT 的有效类型。我想出了一个解决方案,其中要打印的值被包装在一个printable模板函数中。然后,此函数利用模板专用化来提供使用nullptr_t时所需的行为。

#include <cstddef>
#include <iostream>
template <typename T> struct Printable
{
    Printable(const T& val) : val(val) {}
    void print(std::ostream& out) const {out << val;}
    const T& val;
};
template <> struct Printable<std::nullptr_t>
{
    Printable(nullptr_t) {}
    void print(std::ostream& out) const {out << "null";}
};
template <typename T>
Printable<T> printable(const T& value) {return Printable<T>(value);}
template <typename T>
std::ostream& operator<<(std::ostream& out, const Printable<T>& p)
{
    p.print(out);
    return out;
}
int main() {
    std::cout << printable(42) << " " << printable(nullptr) << "n";
    return 0;
}

Ideone link