D discards top level array’s const during implicit functions instantiation and leaves it in case of explicit one.
Consider code:
// main.d
import std.stdio;
void foo( T )( T val )
{
writeln( typeid( T ) );
}
void main()
{
const int[] arr;
writeln( typeid( arr ) ); // actual type
foo( arr ); // implicit instantiation
foo!( typeof( arr ) )( arr ); // explicit instantiation
}
…and output:
$ dmd main.d && ./main const(const(int)[]) const(int)[] const(const(int)[])
As you can see, top level const was lost in case of implicit instantiation. Is this bug, feature or my misunderstanding ?
What’s lost is the constness of the array pointer – not the constness of the array itself.
const int[]in D protects both the array pointer(you can’t point it to a different array) and the array data(you can’t change the elements). That’s why the first and third outputs have 2consts in them. However, when you pass the array to the function, there is no need to keep the constness of the pointer – if you changevalinsidefooto a different array, it won’t effect the content ofarrin themainfunction.