Template class with dispatched properties
Chris Cain
clcain at uncg.edu
Thu Nov 7 20:05:50 PST 2013
On Friday, 8 November 2013 at 03:42:12 UTC, Ross Hays wrote:
> I am actually a little curious why my original approach did not
> work at all. Using some of what you provided and some of what I
> had I get the following:
>
> import std.stdio;
> import std.string;
>
> class Vector(int N, T) if (N <= 3) {
> T[N] data;
>
> this()
> {
> data[] = 0;
> }
>
> @property ref T opDispatch(string fieldName, Args ...)(Args
> args)
> if (Args.length < 2 && fieldName.length == 1 &&
> toOffset(fieldName) < N)
> {
> int offset = fieldName.charAt(0) - 'x';
> return data[offset] = args[0];
> }
> }
>
> void main()
> {
> Vector!(2, float) t = new Vector!(2,float)();
> writeln(t.x);
> }
>
> Which still errors out with: Error: no property 'x' for type
> 'test.Vector!(2, float).Vector'
>
> So that is odd.
Strange. I'm getting a different error, but I'm still running
2.063.2.
The error I get is
`Error: cannot resolve type for t.opDispatch!("x")`
What version are you running?
In any case, the reason apparently is multifold:
1. Apparently the proper error message isn't shown when using the
property notation. (I'd have to check to see if it happens in
2.064 ... might be a fixed bug)
2. `.charAt(0)` doesn't exist for D's strings. You can just use
bracket notation to access the index.
3. When args is empty (as it will be for a getter, when you call)
args[0] doesn't exist, so `Error: array index [0] is outside
array bounds [0 .. 0]`
So fix 2 and 3 and it works for getting x. The reason I use a
static if is to separate the cases where args has items and when
it does not (since args[0] is invalid when args.length == 0), so
that'll be necessary to get it to work.
More information about the Digitalmars-d-learn
mailing list