On Sunday, 6 January 2013 at 11:32:40 UTC, Jacob Carlborg wrote:
On 2013-01-05 23:40, michaelc37 wrote:
i was trying to make a D template to mimic auto-implemented
properties in c#.

I think i got it to work but when i tried to give the template a
more meaning full name like AutoImplementedProperty i get a
compile error "a.title is not an lvalue".
Is this a bug?
Is there a more suitable way of doing this?

c# e.g:
class Bar
{
    public string Title { get; set; }
}

my attempt:
class Bar
{
    alias autoproperty!(string, "get", "set") title
}

template autoproperty(T, args...)
{
    import std.typetuple;
    @property
    {
        private T _name;
        static if (args.length)
        {
            static if (staticIndexOf!("get", args) > -1)
            {
                public T autoproperty()
                {
                    return _name;
                }
            }

            static if (staticIndexOf!("set", args) > -1)
            {
                public void autoproperty(T value)
                {
                    _name = value;
                }
            }

        }
    }
}

void main(string[] args)
{
    Bar a = new Bar();
    a.title = "asf";
    writefln(a.title);

    return;
}

This won't work like you think it will. All instances of "Bar" will share the same "_name" variable.

You need to use a mixin. This pass:

void main ()
{
    Bar a = new Bar();
    a.title = "asf";

    Bar b = new Bar;
    assert(b.title == a.title);
}

Yea i realized that later, but the only fix i could come up with required me passing the property name in the template parameters, so the declaration has changed a bit.

second attempt;

class Bar
{
        public mixin autoproperty!(string, "title", "get", "set");
        public mixin autoproperty!(string, "description", "get", "set");
}

mixin template autoproperty(T, alias propertyName, args...)
{
        import std.typetuple;

        mixin("private T _" ~ propertyName ~ ";");
                
        @property
        {               
                static if (args.length)
                {
                        static if (staticIndexOf!("get", args) > -1)
                        {
                                mixin("
                                T " ~ propertyName ~ "()
                                {
                                        return _" ~ propertyName ~ ";           
                      
                                }");
                        }
        
                        static if (staticIndexOf!("set", args) > -1)
                        {
                                mixin("
                                void " ~ propertyName ~ "(T value)
                                {
                                        _" ~ propertyName ~ " = value;
                                }");
                        }                       
                }
        }       
}


Reply via email to