Why can't structs be derived from?
Daniel Gibson
metalcaedes at gmail.com
Tue Mar 15 18:26:15 PDT 2011
Am 16.03.2011 02:01, schrieb bearophile:
> Andrej Mitrovic:
>
>> I've spotted this in QtD's codebase, dunno if this works:
>>
>> T static_cast(T, U)(U obj)
>> {
>> return cast(T)cast(void*)obj;
>> }
>
> See this thread, it contains a better implementation of staticCast (partially written by me), that I'd like in Phobos:
> http://www.digitalmars.com/d/archives/digitalmars/D/learn/Dynamic_and_Static_Casting_24524.html
>
> Bye,
> bearophile
The only difference is that it checks that both T and U are classes and
T is the base class of U, or did I miss something?
This check may make sense, but this cast could even work on
pointers-to-structs if they are similar, something like
struct Foo { int x; }
struct Bar {int x; int y; }
...
Bar *b = new Bar();
b.x = 42;
Foo *f = static_cast!(Foo*, Bar*)(b);
assert(f !is null);
assert(f.x == 42);
of course this is kind of ugly and hackish, maybe even non-portable and
also works on classes that are not derived from each other without any
complaint (that will probably result in strange errors when using
methods) - so your version is much safer.
Not sure if allowing this kind of casts for (pointers to) structs makes
sense - maybe some C-code uses this to emulate inheritance (I seem to
recall that Quake2 uses hacks like this)?
More information about the Digitalmars-d
mailing list