digitalmars.D - Excesive use of opIndex* in std.container.Array (and Ranges in
- monarch_dodra (41/41) Jul 02 2012 When I read the "D programming language" chapter on operator
- Andrei Alexandrescu (3/10) Jul 02 2012 I agree. There should be an enhancement request for this.
When I read the "D programming language" chapter on operator overloading, I found that the fact there were operators "opIndexAssign", "opIndexOpAssing" and "opIndexUnary" to be nothing short of brilliant. Finally, a container of bools that works for real! However, if and when "opIndex" is capable of returning a reference, isn't defining the above symbols gratuitous, error prone, and worse, actually restrictive? Case in point: ---- import std.container; import std.stdio; void main() { Array!int ai; ai.length = 3; ++ai[0]; //Does not compile because the implementation forgot to define opIndexUnary ai[0] = ai[1] = 5; //Does not compile because opIndexAssign does not return a value ++(++ai[0]); //Can't compile (even if opIndexUnary existed) (ai[0] += 5) += 5; //Can't compile } ---- Here, there are 4 lines: The first doesn't compile simply because we forgot to define the operator in the class. The second because the return value of OpIndexAssign is defined as void. Finally, the third and fourth simply can't compile, because "opIndexOpAssing" and "opIndexUnary" can't be chained, at least not without extra language support (and even then, you'd have to pay for re-indexing every time). If Array simply defined "ref T opIndex(size_t i)" (which it is perfectly capable of doing), and didn't define anything else, then all of the above would work. Lines 1 & 2 don't work because of implement details, but can be fixed. 3 & 4 simply can't be fixed. In the case of containers that are capable of returning refs, is there really a point to rolling out more code, just to get less? (This, of course, does not hold for Array!bool, or any other container that can't return refs)
Jul 02 2012
On 7/2/12 4:13 AM, monarch_dodra wrote:When I read the "D programming language" chapter on operator overloading, I found that the fact there were operators "opIndexAssign", "opIndexOpAssing" and "opIndexUnary" to be nothing short of brilliant. Finally, a container of bools that works for real! However, if and when "opIndex" is capable of returning a reference, isn't defining the above symbols gratuitous, error prone, and worse, actually restrictive?I agree. There should be an enhancement request for this. Andrei
Jul 02 2012