On Thursday, 15 March 2018 at 15:48:52 UTC, James Blachly wrote:
On Wednesday, 14 March 2018 at 22:58:25 UTC, ag0aep6g wrote:
You can probably get around the (manually maintained?) `FIELDS` array with `.tupleof` or something similar:

----
static foreach (i, f; S.tupleof)
{
    case __traits(identifier, f):
}
----

Any pointers / design patterns on this particular type of problem class would be greatly appreciated.  (Sidenote, I realize I could probably use the witchcraft library, but I am also using this as exercise to learn D beyond the basics).

You simply cannot have a method that returns different types based on a run-time value. You could possibly return a std.variant.Variant. But if the goal is just to print the value to the screen, all you need is a string.

So the signature would be `string get(string field)`. And for the implementation you could use `.tupleof` to iterate over all fields, and then return `f.to!string`.

`set` can be done similarly. Take two `string`s: the field name, and the value. `static foreach` over all fields. On a match, convert the given value string to the type of the field that matched.

Thanks - to!string certainly seems to be a good option in this case (CLI) and I was definitely overthinking this part, perhaps because I was trying to write everything as generically / extensibly as possible (for example, to use the same framework but with a GUI or web front end, for example).

I would still think an AA mapping (string) field name to a type would be useful and will see if I can construct it as a mixin using typeof(Struct.member) somehow.

If you're comming from python you may appreciate that you don't need getter/setters in D either. Just as you have @property in python which allows you to change at any time from a simple attribute to a method (be it reading or writing) you have a property syntax in D:

    struct S {
        int a;

        int _b;

        auto b() {
            return _b;
        }

        void b(int val) {
            _b = val;
        }
    }


    void main(string[] args) {
        S s;
        s.a = 24;
        writeln(s.a);

        s.b = 42;
        writeln(s.b);
    }

Reply via email to