将输出流上的`nullptr`格式化为十六进制地址,而不是`0`

问题描述

如何在输出流中格式化任何类型的空指针,最好包括立即数nullptr,以便它像0x000000000000甚至什至0x0一样打印出来,但是类似于地址值而不是毫无意义的0 terminate 或任何非地址形式的东西? // (nil)(null)如果不使用printf也可以接受。

解决方法

您可以制作一个指针格式化程序,该格式化程序可以按照您喜欢的任何方式进行格式化。

例如:

#include <cstdint>
#include <iomanip>
#include <ios>
#include <iostream>
#include <sstream>
#include <string>

static auto Fmt(void const* p) -> std::string {
    auto value = reinterpret_cast<std::uintptr_t>(p);
    constexpr auto width = sizeof(p) * 2;
    std::stringstream ss;
    ss << "0x" << std::uppercase << std::setfill('0') << std::setw(width) << std::hex << value;
    return ss.str();
}

int main() {
    char const* p = nullptr;
    std::cout << Fmt(p) << "\n";
    p = "Hello";
    std::cout << Fmt(p) << "\n";
}
,

您可以重载

#include <iostream>

struct Foo {
    void bar() {}
};

std::ostream& operator<<(std::ostream& stream,void *p) {
    return stream << 0 << 'x' << std::hex << reinterpret_cast<size_t>(p) << std::dec;
}

int main() {
    Foo foo;
    Foo *p = &foo;

    std::cout << p << std::endl;
    p = nullptr;
    std::cout << p << std::endl;
}

或者添加一个更灵活的包装器,因为您可以使用这两种方法,但是需要更多的输入。

#include <iostream>

struct Foo {
    void bar() {}
};

struct Pointer_wrapper {
    void *p_;
    explicit Pointer_wrapper(void *p) :p_(p) {}
};

std::ostream& operator<<(std::ostream& stream,const Pointer_wrapper& w) {
    return stream << 0 << 'x' << std::hex << reinterpret_cast<size_t>(w.p_) << std::dec;
}

using pw = Pointer_wrapper;

int main() {
    Foo foo;
    Foo *p = &foo;

    std::cout << pw(p) << std::endl;
    p = nullptr;
    std::cout << pw(p) << std::endl;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...