Re: static_cast<Type1*>(Type2*) not working, but (Type1*) Type2* works
On Aug 10, 7:11 am, Juha Nieminen <nos...@thanks.invalid> wrote:
Preben <64bitNOSPA...@mailme.dk> wrote:
However this works with no problems:
const rw::kinematics::Frame* f = (rw::kinematics::Frame*) joints[i];
Of course it works. A C-style cast will cast from anything to anythin=
g.
A static_cast, however, is designed to reject casting between
incompatible types (or from const to non-const).
Well, no quite. IIRC, a C-style cast still won't do some kinds of
casts, such as:
1- a pointer type to an integer type which isn't big enough to hold
the pointer value.
void* p;
short s = (short)p;
http://www.comeaucomputing.com/tryitout/
"ComeauTest.c", line 2: error: invalid type conversion
short s = (short)p;
2- a class type to a pointer. Ex:
struct A {};
A a;
void* p = (void*)a;
http://www.comeaucomputing.com/tryitout/
"ComeauTest.c", line 3: error: no suitable conversion function from
"A" to "void *"
exists
void* p = (void*)a;
3- a derived class to ambiguous base class. Ex:
struct A {};
struct B : A {};
struct C : A {};
struct D : B, C {};
D* d = new D;
A* a = (A*)d;
http://www.comeaucomputing.com/tryitout/
"ComeauTest.c", line 6: error: base class "A" is ambiguous
A* a = (A*)d;
This one is my favorite example because a reinterpret_cast will "do
it". The answer is as long as the types are related by inheritance
(and the types's definitions are in scope), then the C-style cast is
equivalent to a static_cast, which can and will fail if it's a cast to
an ambiguous base class. The reinterpret_cast happily just copies the
bit pattern (for the common implementation).
And I'm sure there are other examples where a C-style cast will not
compile.