On Sunday, 8 January 2017 at 20:30:26 UTC, Eugene Wissner wrote:
On Sunday, 8 January 2017 at 20:11:23 UTC, Brian wrote:
On Friday, 6 January 2017 at 17:48:23 UTC, Eugene Wissner wrote:
On Friday, 6 January 2017 at 17:44:13 UTC, Brian wrote:
I would like to design features, how should I do?

coding:

class User
{
        @GenerateProperty
        int id;
        
        @GenerateProperty
        string name;
}

struct GenerateProperty
{
        this(string propertyName)
        {
                propertyName = propertyName
        }
        
        string propertyName;
        
        string getGenerateCode()
        {
return "@property int " ~ propertyName ~ "() { return __" ~ propertyName ~ "; }\n@property int " ~ propertyName ~ "(int value) { return __" ~ propertyName ~ " = value; }";
        }
}

result code:

class User
{
    @property int id() { return __id; }
    @property int id(int value) { return __id = value; }
        
    @property string name() { return __name; }
@property string name(int value) { return __name = value; }
        
        private
        {
                int __id;
                string __name;
        }
}

Look into https://github.com/funkwerk/accessors for the implementation. You should have a mixin which iterates through all class members and generates the properties.

Can write this code to impl it?

import accessors;
import std.stdio;

class Base
{
    mixin(GenerateFieldAccessors);
}

class Person : Base
{
    @Read @Write
    private uint age_;

    @ConstRead
    private string name_;

    this(in string name, in uint age = 0)
    {
        this.name_ = name;
        this.age_ = age;
    }
}

void main()
{
    auto person = new Person("Saul Kripke");

    person.age = 57;

    writeln(person.name, ": ", person.age);
}

I think you have to include "mixin(GenerateFieldAccessors);" into "Person" class. accessors has currently a problem with inheritance. We're looking for a way to fix it. I gave a link, so you can take a look how it is implemented. But you can also use the library if it meets your needs :) But yes you can define a enum mixin which iterates through the class members and generates the code:

template GenerateFieldAccessorMethods()
{
    static enum GenerateFieldAccessorMethods()
    {
        foreach (name; __traits(allMembers, typeof(this)))
        {
            return "Generated code";
        }
}

and then you can include it in the class/struct with "mixin(GenerateFieldAccessorMethods!());".

I see, man!

If the parent class cannot generate code for a subclass, it's not as good as a high-level programing language.

Reply via email to