[Issue 7753] Support opIndexCreate as part of index operator overloading in user-defined types
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Fri Mar 23 03:28:33 PDT 2012
http://d.puremagic.com/issues/show_bug.cgi?id=7753
Dmitry Olshansky <dmitry.olsh at gmail.com> changed:
What |Removed |Added
----------------------------------------------------------------------------
CC| |dmitry.olsh at gmail.com
--- Comment #1 from Dmitry Olshansky <dmitry.olsh at gmail.com> 2012-03-23 03:28:52 PDT ---
It might be a good thing, but ...
Why not just return a proxy type upon each indexing?
The proxy type will have createIndex that will forward to others in turn.
Here a prof of concept I belive it could be generalized and polished.
For simplicity sake it's for n-dim arrays:
import std.stdio, std.exception;
struct Proxy(T)
{
T* _this;
int idx;
void opAssign(X)(X value){
debug writeln("Proxy.opAssign");
createIndex(idx) = value;
}
static if(typeof(*_this).dimension >= 2)
{
// somewhere io expression ...a[idx][jdx]... is create all, except last
one
auto opIndex(int jdx){
return proxy(&_this.createIndex(idx), jdx);
}
//a[idx][jdx] = y; is create if non-existent
auto opIndexAssign(X)(X val, int jdx){ //TODO: constraints!
debug writeln("Proxy.opIndexAssign");
_this.createIndex(idx).createIndex(jdx) = val;
}
}
@property ref expr(){
debug writeln("Proxy.expr");
return _this.normalIndex(idx);
}
alias expr this;
}
auto proxy(T)(T* x, int idx){ return Proxy!(T)(x,idx); }
struct M(size_t dim)
{
static if(dim == 1){
alias int Val;
}
else{
alias M!(dim-1) Val;
}
enum dimension = dim;
Val[] arr;
ref createIndex(int idx){
debug writeln("Created ", typeof(this).stringof);
if(arr.length < idx)
arr.length = idx+1;
return arr[idx];
}
ref normalIndex(int idx){
debug writeln("Indexed ", typeof(this).stringof);
return arr[idx];
}
auto opIndex(int idx){
return Proxy!(M)(&this, idx);
}
alias arr this;
}
unittest{
M!(3) d3arr;
d3arr[1][2] = [2, 3, 4];
assert(d3arr[1][2][2] == 4);
int[] x = d3arr[1][2];
assert(d3arr[1][2].length == 3);
assert(d3arr[1][1] == null); //inited
//booom used before explicit =
assert(collectException!Error(d3arr[2][2][1] + 1 == 1) !is null);
}
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
More information about the Digitalmars-d-bugs
mailing list