Topic: Q: How do I cout a const pointer?


Author: fjh@munta.cs.mu.OZ.AU (Fergus Henderson)
Date: Mon, 22 Aug 1994 10:46:02 GMT
Raw View
plessel@fred.rtpnc.epa.gov (Todd Plessel) writes:

>// A simple question: How can I cout a const pointer? (I want the address to
>// be printed.) What is the proper (non-cast) way of doing this?

There isn't one.  This is a bug in the standard.

As a workaround, use the following:

 inline ostream& operator<<(ostream& o, const void *p) {
  cout << const_cast<void *>p;
 }

--
Fergus Henderson - fjh@munta.cs.mu.oz.au




Author: plessel@fred.rtpnc.epa.gov (Todd Plessel)
Date: 12 Aug 1994 17:01:19 GMT
Raw View
// A simple question: How can I cout a const pointer? (I want the address to
// be printed.) What is the proper (non-cast) way of doing this? (It must work
// when the type is unknown i.e., within a parameterized class of type T.)
// (I'm not as familiar with streams as I need to be, but I'd like to purge the
// remaining printf calls from my C++ code.)
// Please e-mail the solution to plessel@vislab.epa.gov.
// Thank you.

#include <iostream.h>

int main()
{
  int i = 88;
  const int* p = &i; // Note the const specifier.
  cout << p << endl; // I get a compile time error here. If I remove (or cast
  return 0;          // away) the const it "works". Is this a compiler bug?
}