Implicit castable structs

Dan murpsoft at hotmail.com
Wed Jan 9 01:57:39 PST 2008


Kris Wrote:

> Yeah, that's old-school inheritance. But I think it's probably a bit dodgy 
> to sidestep type-safety to do what you want. Besides, it's not hard to write 
> this instead (the old school way):
> 
> #  gtk_widget_foo (&bin->container.widget);
> 
> the codegen will be the same as just using 'bin' by itself, yet the 
> type-safety is fully retained.
> 
> On the other hand, if there were an opCast() in the struct to support what 
> you're suggesting ....
> 
> - Kris
> 
> 
> 
> "Frank Benoit" <keinfarbton at googlemail.com> wrote in message 
> news:fm0vht$1tv7$1 at digitalmars.com...
> > In GTK programming, there are struct that act like a object hierarchy.
> >
> > struct GtkWidget{ /* data member */ }
> > struct GtkContainer{
> > GtkWidget widget; // parent is always first member
> > // more data members
> > }
> > struct GtkBin{
> > GtkContainer container; // parent is always first member
> > // more data members
> > }
> > extern(C) void gtk_widget_foo( GtkWidget* widget );
> >
> > // in user code ...
> > GtkBin* bin;
> > gtk_widget_foo( bin ); // Error: cannot implicit cast
> >
> > Can the D compiler be enhanced to allow this? More precisely:
> > "A pointer to a struct is implicitly convertable to all types, that map to 
> > the first position in the struct"
> >
> > In the case above, a GtkBin* would be convertable to GtkContainer* and 
> > GtkWidget*. A GtkContainer* would /not/ be convertable to GtkBin* because 
> > it does not contain it.
> > 
> 

Multiple opCast is the #2 requested feature on that "vote for D changes" website, and IMHO the most desireable one for my project.

My code would be dramatically more attractive... *gorgeous* if you could do the following:

struct Value {
const(char)[] opCast() {
  bla bla bla
}
int opCast() {
  bla bla bla
}

and:

Value myfunc() {
  return 4;  // performs opAssign()
}

Regards, Dan.



More information about the Digitalmars-d mailing list