Override member variables

Ali Çehreli acehreli at yahoo.com
Sat May 19 19:58:02 UTC 2018


On 05/19/2018 11:09 AM, Gheorghe Gabriel wrote:
 > I've worked with a lot of programming languages and I've found something
 > interesting in Kotlin. You can override member variables. Would you like
 > to have this feature in D?

It's needed in C++ and I'm sure any object-oriented programming language 
as well. As you seem do indicate, the current solution is to provide 
member functions. Assuming that the values are constant:

class Rectangle {
     int width() const {
         return 0;
     }
     int height() const {
         return 0;
     }
}

class Table : Rectangle {
     override int width() const {
         return 10;
     }
     override int height() const {
         return 14;
     }
}

void main() {
     auto r = new Table();
     assert(r.width == 10);
     assert(r.height == 14);
}

The compiler can optimize virtual function calls away when it can prove 
the actual type.

Here is quick exercise with current language features:

mixin template overridable(string name, T...) {
     static assert(T.length == 1, "You must provide a single value for 
member '" ~ name ~"'");

     import std.string : format;
     mixin (format(q{
                 %s %s() const { return %s; }
             }, typeof(T[0]).stringof, name, T[0]));
}

mixin template overrided(string name, T...) {
     static assert(T.length == 1, "You must provide a single value for 
member '" ~ name ~"'");

     import std.string : format;
     mixin (format(q{
                 override %s %s() const { return %s; }
             }, typeof(T[0]).stringof
             , name, T[0]));
}

class Rectangle {
     mixin overridable!("width", 0);
     mixin overridable!("height", 0);
}

class Table : Rectangle {
     mixin overrided!("width", 10);
     mixin overrided!("height", 14);
}

void main() {
     auto r = new Table();
     assert(r.width == 10);
     assert(r.height == 14);
}

Ali



More information about the Digitalmars-d mailing list