copy must be const?!?

Dennis dkorpel at gmail.com
Wed Jul 24 15:40:28 UTC 2024


On Wednesday, 24 July 2024 at 15:08:28 UTC, Dom DiSc wrote:
> Why is this copy const?!? If I copy a const or immutable 
> object, most of the time I do so because I want to work with 
> this value.

Because the compiler instantiates `test2!T` deriving T from the 
type of the argument you pass to `x`, which is `const(int)`. This 
is indeed an annoyance with const, and there's even some special 
treatment for arrays such that passing a `const char[]` will 
instantiate with `const(char)[]`, which is necessary to make 
ranges work. There's a DIP trying to generalize this behavior to 
user-defined types, but it's WIP: 
https://forum.dlang.org/thread/ut4f3m$2e4a$1@digitalmars.com

> Is there a way to tell the compiler that it should discard 
> "const" and "immutable" if it needs to create a copy?
> Unqual!T doesn't work :-(

When you add `const` or `immutable` before the template type 
parameter, it will infer T as simply `int`:

```D
T test2(T)(immutable T x) { return --T(x); }
```


More information about the Digitalmars-d-learn mailing list