identof || toIdent - feature suggestion / question
Derek Parnell
derek at nomail.afraid.org
Sun Jul 2 23:28:43 PDT 2006
On Sun, 02 Jul 2006 17:21:52 +0800, Daniel Keep wrote:
> The problem with templates/mixins at the moment is that they can't
> generate new identifiers. For example, I'd love to be able to do this:
>
> # mixin attribute!(int, "foo", Public /*read*/, Private /*write*/);
>
> Which would save a huge amount of essentially useless boilerplate code.
> The problem is, of course, that I can't generate that "foo" properly.
> The only way to do it is to manually declare the storage, and then
> alias the getter and setter seperately... and then it ends up being just
> as long as writing it manually.
I just had a play around with an idea that might be useful here...
=======================
import std.stdio;
template AttributeAll(T)
{
private T _xA;
public T get() { return _xA; }
public T set(T d) { _xA = d; return d; }
}
template AttributeAll(T, alias F)
{
private T _xAF;
public T get() { return F(_xAF,true); }
public T set(T d) { _xAF = F(d,false); return F(_xAF,true); }
}
template AttributeRO(T)
{
private T _xR;
public T get() { return _xR; }
}
template AttributeRO(T, alias F)
{
private T _xRF;
public T get() { return F(_xRF, true); }
}
template AttributeWO(T)
{
private T _xW;
public T set(T d) { _xW = d; return _xW; }
}
template AttributeWO(T, alias F)
{
private T _xWF;
public T set(T d) { _xWF = F(d,false); return F(_xWF,true); }
}
class Car
{
mixin AttributeAll!(int, QA_Colour) Colour;
mixin AttributeAll!(real) Speed;
mixin AttributeRO!(real) Torque;
mixin AttributeWO!(real, QA_Accel) Accel;
mixin AttributeAll!(char[]) Name;
// Set torque on acceleration
private real QA_Accel(real v, bool act)
{
if (act == false)
{
Torque._xR = v * 17 / 3;
}
return v;
}
// Validate Colour
private int QA_Colour(int v, bool act)
{
if (act == false)
{
if (v >= 0 && v < 256)
Colour._xAF = v;
else throw new Error("Bad colour value.");
}
return v;
}
}
void main()
{
auto sample = new Car;
sample.Name.set = "Furary";
sample.Colour.set = 4;
sample.Speed.set = 6.4455;
sample.Accel.set = 1.2;
writefln("%s ...\n Colour %s, Speed %s, Torque %s",
sample.Name.get,
sample.Colour.get,
sample.Speed.get,
sample.Torque.get
);
}
=====================
This could be a starting point for better property implementation ?
--
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
3/07/2006 4:25:24 PM
More information about the Digitalmars-d
mailing list