Struct "inheritance"
Ali Çehreli
acehreli at yahoo.com
Sat Feb 4 08:25:01 PST 2012
On 02/04/2012 03:38 AM, Vidar Wahlberg wrote:
> Let's say I got a struct for a location on a 2-dimensional plane:
> struct Point {
> int x;
> int y;
> }
> Further I also need to represent a location in a 3-dimensional space:
> struct Coordinate {
> int x;
> int y;
> int z;
> }
> If these were classes instead I could simply make Coordinate inherit
> from Point and only add "int z;".
There is also template mixins to inject complete features into the code
(similar to C macros but without their gotchas).
The following templatizes the coordinate types, but you could use put
write everywhere:
import std.stdio;
template Point2D(T)
{
T x;
T y;
void foo2D()
{
writefln("Using (%s,%s)", x, y);
}
}
struct Coordinate(T)
{
mixin Point2D!T; // <-- Inject x, y, and foo2D() here
T z;
this(T x, T y, T z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
void main()
{
auto c = Coordinate!double(1.1, 2.2, 3.3);
c.foo2D();
}
You could insert the following line in any other scope and you would
have x, y, foo2D() inserted right there as well:
if (someCondition) {
mixin Point2D!T; // <-- Inject x, y, and foo2D() here
// ... use the local x, y, and foo2D() here
}
Of course 'static if' may be even more suitable in other cases.
Ali
More information about the Digitalmars-d-learn
mailing list