Templated opIndex?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Sep 19 22:47:21 PDT 2015


On 09/19/2015 02:33 AM, OlaOst wrote:
 > Here is a class with a templated opIndex method, and an attempt to 
use it:
 >
 > class Test
 > {
 >      int[] numbers = [1, 2, 3];
 >      string[] texts = ["a", "b", "c"];
 >
 >      Type opIndex(Type)(int index)
 >      {
 >          static if (is(Type == int))
 >              return numbers[index];
 >          static if (is(Type == string))
 >              return texts[index];
 >      }
 > }
 >
 > void main()
 > {
 >      auto test = new Test();
 >
 >      auto number = test[0]!int; // does not compile, syntax error
 >      auto number = test!int[0]; // does not compile, syntax error
 >
 >      int number = test[0]; // does not compile, cannot deduce type
 > }
 >
 >
 > So it is possible to define a templated opIndex method in a class, but
 > is it possible to use it? If not, should it be allowed to create
 > templated opIndex methods?

Templated opIndex is used for multi-dimensional array indexing. The 
template arguments define the range of elements:

 
http://ddili.org/ders/d.en/templates_more.html#ix_templates_more.opIndex%20template

And the spec:

   http://dlang.org/operatoroverloading.html#array-ops

I would prefer the following:

   test.numbers[0];
   test.texts[0];

but in addition to other solutions, here is another experiment:

struct indexFor(T)
{
     size_t idx;
}

class Test
{
     int[] numbers = [1, 2, 3];
     string[] texts = ["a", "b", "c"];

     T opIndex(T)(indexFor!T index)
     {
         static if (is(T == int))
             return numbers[index.idx];
         static if (is(T == string))
             return texts[index.idx];

         assert(false);
     }
}

void main()
{
     auto test = new Test();

     auto number = test[indexFor!int(0)];
}

Ali



More information about the Digitalmars-d-learn mailing list