compile-time opIndex

Artur Skawina via Digitalmars-d digitalmars-d at puremagic.com
Thu Jan 1 06:23:33 PST 2015


On 12/31/14 22:35, H. S. Teoh via Digitalmars-d wrote:
> On Wed, Dec 31, 2014 at 10:34:07PM +0100, Artur Skawina via Digitalmars-d wrote:
>> On 12/18/14 16:43, Steven Schveighoffer via Digitalmars-d wrote:
>>> 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.
>>
>>    struct TupleWannabe(S) {
>>       typeof(S.tupleof) tupleof;
>>
>>       static __memberWannabe() {
>>          string s;
>>          foreach (I, _; typeof(S.tupleof))
>>             s ~= `ref `~S.tupleof[I].stringof~`() @property {
>>                      return tupleof[`~I.stringof~`];
>>                   } `;
>>          return s;
>>       }
>>       mixin(__memberWannabe());
>>
>>       alias tupleof this;
>>    }
>>    
>>    struct S {
>>       int key;
>>       string val;
>>    }
>>
>>    alias ST = TupleWannabe!S;
>>
>>    void main() {
>>       ST s = ST(1, "blah");
>>       s.key = 2;
>>       s.val = "yada";
>>       s[0] = 42;
>>       s[1] = "etc";
>>    }
>>
>> SCNR. Happy new year!
> 
> Very nice! Now make it work for int* and string*, but indexing the tuple

OP only asked for tuple-like indexing for UDTs.

> returns (non-pointer) int and string. This is the original use case that
> prompted this ER, btw, so if it can't be achieved, then we haven't
> solved anything.

That is not supported by the _language_. It lacks (1) references and
(2) means of controlling object lifetimes. You can easily add a `Ref!`
wrapper, but, because of the latter issue, these types of hacks are
not a good idea in general.

artur


More information about the Digitalmars-d mailing list