Templated opIndex?
OlaOst via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Sep 19 02:33:00 PDT 2015
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?
More information about the Digitalmars-d-learn
mailing list