在C ++流中禁用指针输出? [英] Disabling pointer output in C++ streams?

查看:222
本文介绍了在C ++流中禁用指针输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你指向C ++流的任何指针,它的地址将被放入输出。 (显然,除非有更具体的输出处理程序。)

If you hand any pointer to a C++ stream, it's address will be put into the output. (Obviously unless there's a more specific output handler.)

void* px = NULL;
const char* ps = "Test";
FooType* pf = ...;
stringstream s;
s << ps << " " << px << " " << pf "\n";
s.str(); // yields, for example: "Test 0 AF120089"

这可能是一个问题,如果用户错误地试图实际打印FooType的

This can be a problem, if the user erroneously was trying to actually print the value of FooType.

当混合宽字符和窄字符时,这也是一个问题,因为不是编译器错误,你会得到打印的地址:

And it is also a problem when mixing wide char and narrow char, because instead of a compiler error, you'll get the address printed:

const wchar_t* str = L"Test! (Wide)";
// ...
cout << str << "\n"; // Ooops! Prints address of str.

所以我想知道 - 因为我很少想输出一个指针值,可以禁用指针值的格式化,以便将指针值插入流中将导致编译器错误?(然后可以通过使用包装器类型或将指针值投射到size_t或somesuch。)

So I was wondering - since I very rarely want to output a pointer value, would it be possible to disable formatting of pointer values, so that inserting a pointer value into a stream would result in a compiler error? (Outputting of pointer values could then be easily achieved by using a wrapper type or casting the pointer values to size_t or somesuch.)

编辑:根据 Neil的回答(通过提供我自己的void *输出运算符禁用void *输出)我想补充一点,如果这也工作对于诸如Boost.Format之类的工具隐式使用 std 命名空间中定义的输出操作符...

In light of Neil's answer (disabling void* output by providing my own void* output operator) I would like to add that it would be nice if this also worked for tools such as Boost.Format, that make implicit use of the output operator defined in the std namespace ...

推荐答案

如果cout的第二个和/或第三个输出未注释,这将导致g ++中的编译错误:

This gives a compilation error in g++ if the second and/or third output to cout is uncommented:

#include <iostream>
using namespace std;

ostream & operator << ( const ostream &, void * ) {
}


int main() {
    int n = 0;
    cout << 0;
//  cout << &n;
//  cout << (void *) 0;
}

这篇关于在C ++流中禁用指针输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆