我如何格式化任何类型的空指针,最好包括立即的nullptr
,在输出流上,这样它就会像0x0000000000
或甚至只是0x0
一样输出,但是类似于地址值的东西,而不是毫无意义的0
,或者终止或任何非类似于地址的东西? //(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";
}
您可以过载<<<; void指针的运算符。
#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;
}