IFTI was recently changed with arrays to be tail-const. It would be useful if we could do the same with auto. To quote dsimcha from the newsgroup ( http://www.digitalmars.com/d/archives/digitalmars/D/auto_Top-level_Const_Immutable_152877.html ):
The changes made to IFTI in DMD 2.057 are great, but they reveal another
hassle with getting generic code to play nice with const.
import std.range, std.array;
ElementType!R sum(R)(R range) {
if(range.empty) return 0;
auto ans = range.front;
range.popFront();
foreach(elem; range) ans += elem;
return ans;
}
void main() {
const double[] nums = [1, 2, 3];
sum(nums);
}
test.d(8): Error: variable test9.sum!(const(double)[]).sum.ans cannot
modify const
test.d(14): Error: template instance test9.sum!(const(double)[]) error
instantiating
Of course this is fixable with an Unqual, but it requires the programmer
to remember this every time and breaks for structs with indirection.
Should we make `auto` also strip top-level const from primitives and
arrays and, if const(Object)ref gets in, from objects?
Comment #1 by timon.gehr — 2012-01-27T15:27:42Z
It would make sense in a way, but how would generic code that preserves the const-ness of some value be written nicely with this in place?
Comment #2 by issues.dlang — 2012-01-27T15:37:11Z
Presumably, it would either use the generic type explicitly or use typeof. And if it really wanted const, then it could just use const explicitly.
If the dropping of constness would make the assignment not possible though, I would argue that the constness should be kept. So, then as long as the code isn't in a situation where it doesn't need to keep constness but it _wants_ to, auto works great. Whereas now, it's really easy to get into a situation where you end up with a const or immutable variable when you really didn't want one, just because the template was instatiated with a const or immutable type.
In general though, I think that if you want const or immutable, you use const or immutable rather than auto. So, the fact that auto preserves full constness causes far more problems than it would if it just preserved tail-constness.
Comment #3 by robert.schadek — 2024-12-13T17:58:06Z