To use opDispatch
bearophile
bearophileHUGS at lycos.com
Sun May 23 12:44:31 PDT 2010
BCS:
> I guess I didn't rememeber correctly. Anyway, this work:
>
>
> import std.stdio;
>
> template If(bool b, T, F) { static if(b) alias T If; else alias F If; }
>
> struct S
> {
> int[string] vals;
> template opDispatch(string s)
> {
> If!(T.length == 1, void, int) opDispatch(T...)(T t)
> {
> static if(T.length == 1) vals[s] = t[0];
> else return vals[s];
> }
> }
> }
>
> void main()
> {
> S s;
> s.foo = 5;
> writef("%s\n", s.foo());
> }
It works :-) In my alternative implementations I have never put that () after the new method name.
Using @property here doesn't work.
I have modified (hopefully improved) your version like this:
import std.stdio: writeln;
import std.traits: isImplicitlyConvertible;
struct S(T) {
T[string] data;
template opDispatch(string name) {
@property T opDispatch(Types...)(Types args)
if (!args.length || (args.length == 1 && isImplicitlyConvertible!(Types[0],T))) {
static if (args.length) {
data[name] = args[0];
return args[0];
} else
return data[name];
}
}
}
void main() {
S!long s;
s.foo = 5;
// writeln(s.foo); // err
writeln(s.foo());
}
Bye,
bearophile
More information about the Digitalmars-d
mailing list