digitalmars.D.learn - aliasing/referencing expressions in with statements
- deed (32/32) Apr 21 2016 Often I find myself wanting to alias an expression, such as
- Yuxuan Shui (3/8) Apr 21 2016 Maybe use something like:
- deed (21/23) Apr 22 2016 You can certainly declare temporaries and rely on the compiler
Often I find myself wanting to alias an expression, such as verbose fields, possibly nested. AFAIK, the with statement makes it easier, but not as good as it could have been. What I'd like to express is for example something like this: with( a = instanceA.verboseFieldA.verboseFieldB, b = instanceA.aDescriptiveName, instanceC) { // use a, b and value: b[value] = b[a + value] * (a*value)^^a; } // given: struct A { B verboseFieldA; int[] aDescriptiveName; ... } struct B { int verboseFieldB; ... } struct C { int value; ... } A instanceA; B instanceB; C instanceC; 1) Is it possible to achieve something similar in D now? And if not: 2) Are there any implementation considerations in this direction, extending the with statement?
Apr 21 2016
On Thursday, 21 April 2016 at 23:05:38 UTC, deed wrote:Often I find myself wanting to alias an expression, such as verbose fields, possibly nested. AFAIK, the with statement makes it easier, but not as good as it could have been. What I'd like to express is for example something like this: [...]Maybe use something like: auto a = () => instanceA.verboseFieldA.verboseFieldB;
Apr 21 2016
On Friday, 22 April 2016 at 01:42:11 UTC, Yuxuan Shui wrote:Maybe use something like: auto a = () => instanceA.verboseFieldA.verboseFieldB;You can certainly declare temporaries and rely on the compiler optimizing those away: auto a = instanceA.verboseFieldA.verboseFieldB; auto b = instanceA.aDescriptiveName; auto value = intanceC.value; // use a, b and value If that were considered a sound solution, it would partly undermine the purpose of with statements, except for referring to multiple fields within the same instance, which I guess is common enough and makes it more convenient to express member functions as free functions. However, it seems simple for the compiler to lower such a with statement, so I wonder whether there are any technical reasons not to? I.e: with (a = expressionA, b = expressionB, instanceC) { // access to instanceC's fields and replace a and b // with expressionA and expressionB, respectively. } That would make for very clear expressions while still allowing descriptive field names. Other solutions, as templates or mixins, seem a little too clumsy.
Apr 22 2016