Templated opIndex?

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Sep 19 03:16:56 PDT 2015


On Saturday, 19 September 2015 at 09:33:02 UTC, 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?

2 approaches:
1) use a function instead. E.g. test.get!int(0); isn't too bad
2) If you really want to use [], do something like this:

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

     private struct Idx(T)
     {
         T data;
         auto opIndex(size_t index)
         {
             return data[index];
         }
     }
     auto idx(Type)() @property
     {
         static if (is(Type == int))
             return Idx!(int[])(numbers);
         static if (is(Type == string))
             return Idx!(string[])(texts);
     }
}

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

     auto number = test.idx!int[0];
     auto text = test.idx!string[0];
}



More information about the Digitalmars-d-learn mailing list