New operators opStaticIndex and friends
Exil
Exil at gmall.com
Fri May 17 19:52:53 UTC 2019
On Friday, 17 May 2019 at 17:41:26 UTC, Q. Schroll wrote:
> On Thursday, 16 May 2019 at 22:26:34 UTC, Exil wrote:
>> This doesn't help with the explanation, what special syntax?
>> Maybe an example that works with opStaticIndex and that
>> wouldn't work with opIndex would help. Otherwise I still don't
>> see a problem.
>
> Simple answer is: You cannot overload opIndex aliasing a data
> member and opIndex being a function. If it is a function
> somewhere, it *must* always be a function in that aggregate
> (struct/union/class/interface).
That's what template specialization is exactly for. Exactly how
it can be used:
struct A {
template opIndex(int i) {
static if(i == 0) alias opIndex = member1;
else alias opIndex = member2;
}
int member1;
double member2;
int opIndex( int a, int b ) { return 0; }
int opIndex(T...)( T a ) { return 1; }
}
void main() {
A a;
a[0,0];
a[0];
a.opIndex!0 = 10; // a[0] = 10
a.opIndex!1 = 10.1; // a[1] = 10.1
writeln( a.member1, a.member2 );
}
> It is more flexible not having a name clash. It's easier to
> learn and reason about, too. To me, it has literally no benefit
> using opIndex for static indexing.
>
> Part of a working example: https://run.dlang.io/is/274pNN
So what if you have 2 parameters, one is a runtime value and the
other is a compile time value? Would it be a compile error then?
But then you can implement opIndex and opStaticIndex, so you can
use two runtime values and two compile time values but if for
some reason you need one, instead you will need some hacky work
around to get it to work:
arr[ 0, someRunTimeIndex() ] = 10; // error mixing
compile-time and run-time
int i = 0;
arr[ i, someRunTimeIndex() ] = 10; // ok
More information about the Digitalmars-d
mailing list