const types can't be specialized non-const, if arrays?
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jun 16 13:09:49 PDT 2016
On 6/16/16 3:43 PM, cy wrote:
> I don't get it. Do I have to write a separate template for arrays
> specifically or something?
>
> NonConst foo(Constant: const NonConst, NonConst)(Constant bar) {
> pragma(msg,"NonConst is ",NonConst);
> pragma(msg,"Constant is ",Constant);
> NonConst foo = bar;
> return foo;
> }
>
> void main() {
> const int bar = 42;
> auto baz = foo(bar);
> pragma(msg,typeof(baz));
> baz = 23;
> const(int[]) barr = [1,2,3];
> auto bazz = foo(barr);
> pragma(msg,typeof(bazz));
> bazz[0] = 4;
>
> }
>
> /*
>
> NonConst is int
> Constant is const(int)
> int
> NonConst is const(int)[]
> Constant is const(int)[]
> const(int)[]
> derp.d(16): Error: cannot modify const expression bazz[0]
> Failed: ["dmd", "-v", "-o-", "derp.d", "-I."]
>
> */
>
1. Because const(int)[] is not the same as const(int[]). The former is a
*mutable* array of *constant* integers.
2. Yes, I see that you passed in const(int[]). IFTI was changed a while
back to automatically convert to tail-const versions when implying
parameters (to save on template bloat). So it deduces "Constant" to be
const(int)[].
Also, note that you cannot assign a const item containing references to
a non-const version of it. So even if NonConst was properly deduced, the
function would fail to compile.
-Steve
More information about the Digitalmars-d-learn
mailing list