compile-time opIndex
Steven Schveighoffer via Digitalmars-d
digitalmars-d at puremagic.com
Thu Dec 18 07:43:39 PST 2014
We currently have the ability to do opIndex for simulating an array or
other type indexed at runtime.
But we have no way to simulate the ability of tuple indexing. Such an
ability would unleash a huge amount of possibilities, including
user-defined tuple types.
Let's designate a straw man name: opTupleIndex.
In essence, if you have foo[n], where n is a compile-time constant, then
opTupleIndex would be instantiated (if defined) like:
opTupleIndex!n
Then you can have user-defined tuples that are simple to define:
struct KeyValuePair(K, V)
{
K key;
V value;
enum length = 2;
ref K opTupleIndex(int x) if(x == 0) { return key;}
ref V opTupleIndex(int x) if(x == 1) { return value;}
}
auto x = KeyValuePair!(int, string)(1, "hi");
static assert(typeof(x[0]) == int);
static assert(typeof(x[1]) == string);
x[0] = 4;
x[1] = "hi";
Note here I have all the mechanisms that real tuples have, but I have
control over what happens when accessing each element, and I do not need
opIndex to change its return type based on a runtime parameter (one of
the limitations of the current system).
I'm not huge on tuple usage, so I'm not sure if I'm missing something.
Currently there is some debate as to whether to add a "byPair" range to
builtin AAs, because the return value from 'front' is hard to define.
This might go a long way in helping such a case.
Does this sound like something worth having? We likely would have to
error if both opIndex and opTupleIndex are defined for a specific type.
-Steve
More information about the Digitalmars-d
mailing list