Copying array with const correctness
Vindex9
tech.vindex at gmail.com
Tue Oct 7 18:43:18 UTC 2025
I'm trying to write a function for copying an array. But
something strange is happening with the const correctness. I
cannot remove the constitution for the case of a two-dimensional
array of lines.
```d
import std.stdio;
import std.traits : Unconst;
auto copyArray(T)(const T[] arr) if (!is(T == class)) {
alias E = Unconst!T;
E[] copy = new E[arr.length];
writeln("orig type: ", typeid(T)); // orig type:
const(immutable(char)[])[]
writeln("copy type: ", typeid(E)); // copy type:
const(immutable(char)[])[]
writeln("copy type: ", typeid(Unconst!E)); // copy type:
const(immutable(char)[])[]
static if (is(T : const(E)[])) { // if inner array (doesn't
work)
writeln("No");
for (size_t i = 0; i < arr.length; i++) {
copy[i] = copyArray(arr[i]);
}
} else {
for (size_t i = 0; i < arr.length; i++) {
E elem = arr[i];
copy[i] = elem;
}
}
return copy;
}
void main() {
const string[][] arr = [["ABC", "DEF"], ["GHI", "JKL"]];
writeln(typeid(arr)); //
const(const(const(immutable(char)[])[])[])
auto res = copyArray(arr);
writeln(typeid(res)); // const(immutable(char)[])[][]
}
```
What am I doing wrong?
I want a safe copy: `const string[][] -> string[][]`.
More information about the Digitalmars-d-learn
mailing list