Using memberspaces for a property-like syntax and more
TommiT
tommitissari at hotmail.com
Sat Feb 2 14:10:30 PST 2013
On Saturday, 2 February 2013 at 21:39:45 UTC, TommiT wrote:
> I think we can use template mixins to achieve that:
>
> mixin template add_stuff(alias var)
> {
> memberspace stuff
> {
> typeof(var) opCall() const
> {
> return var;
> }
>
> void opAssign(typeof(var) rhs)
> {
> var = rhs;
> }
> }
> }
>
> struct S
> {
> int _value;
>
> mixin add_stuff!(_value);
> }
>
> void main()
> {
> S s;
> s.stuff = 42;
> assert(s.stuff() == 42);
> }
And here's how you could even add the name of your memberspace as
one of the template mixin parameters:
mixin template basic_property(alias prop, alias var)
{
memberspace prop
{
typeof(var) opCall() const
{
return var;
}
void opAssign(typeof(var) rhs)
{
var = rhs;
}
}
}
struct S
{
int _value;
memberspace myprop { }
mixin basic_property!(myprop, _value);
}
void main()
{
S s;
s.myprop = 42;
assert(s.myprop() == 42);
}
More information about the Digitalmars-d
mailing list