问题描述
如何在输出流中格式化任何类型的空指针,最好包括立即数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;
}