Why can't structs be derived from?

foobar foo at bar.com
Wed Mar 16 15:45:12 PDT 2011


Andrei Alexandrescu Wrote:
> 
> Not to mention that alias this offers the ability of a runtime hook; you 
> don't need structural conformance as you can produce the conversion on 
> the fly.
> 
> Andrei

Are you talking about something like:
struct A { double x, y };

struct  B {
  double radius, phi, teta;  
  A toCartesian() {...}
  alias toCartesian this; 
}

used as: 
auto location = new B(...);
circle.drawAt (location.x, location.y); 
// OR
// where drawAt expects an instance of struct A
circle.drawAt(location); 

It is a powerful feature (but so is MI). This allows the caller to treat the instance as two different types but is this useful? It fells like less readable code to me. compared with the more explicit:
circle.drawAt(location.toCartesian());
I also think it's a feature rarely used. 

As for the example in the thread with structs:
I completely agree with the point about composition vs. inheritance but was it really neseccary to add this IMO butt ugly, unreadable syntax to the language instead of naturally extending already available syntax which is far more readable? 
I.e.

struct Point2D {...} 

struct Point3D {
  mixin Point2D;
  int z; 
}



More information about the Digitalmars-d mailing list