Topic: static_cast of mind


Author: Attila.Feher@lmf.ericsson.se (Attila Feher)
Date: Thu, 5 Sep 2002 18:05:04 +0000 (UTC)
Raw View
Hi All,

There is a thread going on in clc++m about casts.  Scott Meyers had a
very interesting observation, which seems to contradict what the
standard says in 5.2.9/2:

8<----
I'm confused again.  5.2.9/2 says:

  An expression e can be explicitly converted to a type T using a
  static_cast of the form static_cast<T>(e) if the declaration "T t(e);"
is
  well-formed, for some invented temporary variable t (8.5).

I read this as saying that if

  T t(e);

is okay, then

  static_cast<T>(e)

is, too.

But consider this:

  struct Widget {
    Widget(int);
  };

  int x = 10;
  const Widget& rw = x;              // Line 1
  static_cast<const Widget&>(x);     // Line 2

All five of my compilers accept line 1, but 3 of the 5 reject line 2:
VC7
and g++ 3.1 accept it, bcc 5.5.1, MWCW 6.1, and Comeau 4.3 beta #4
reject
it.

Once again I must ask, what am I missing?
---->8

Yes, I did quote nearly everything from Scott, and yes, it should have
been him posting here - but I am just waaay to curious now.  I have
heard many _opinions_ on why the static_cast should not work.  Basically
what I understood boiled down to this:

There are two type transformations here:

int2Widget
Widget2WidgetCRef

And static_cast is not allowed to do more than one type
transformations...  This I understand, but where is it written in the
standard?  The paragraph 5.2.9/3 starts with the word: Otherwise,
meaning that _if_ T t(e) is not working, _then_ we read on.

I am puzzled and cannot sleep (or sleep too much).  First of all:
casting a type to a reference is not really a casting or type
conversion, it is "binding a reference to it".  So one may understand
that the int2Widget is the real casting here, the next step does not
change the type - only puts an alias on the variable...  That one I am
referring to is humble me.

BUT - even if it is not this way: if T t(e) works static_cast<T>(e) must
work - according to 5.2.9/2.  Where is the catch?  Where does the
standard disallow (either explicitly or implicitly) the static_cast
above?

So what is the cast of mind of the static_cast?

Attila

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]