On Thursday, 10 February 2022 at 17:09:23 UTC, Ali Çehreli wrote:
import std.traits : isAssociativeArray,
isImplicitlyConvertible, KeyType, ValueType;
void update(Target, From)(ref Target target, From from)
if (isAssociativeArray!Target &&
isAssociativeArray!From &&
isImplicitlyConvertible!(KeyType!From, KeyType!Target) &&
isImplicitlyConvertible!(ValueType!From, ValueType!Target))
{
foreach (kv; from.byKeyValue) {
target[kv.key] = kv.value;
}
}
[...]
Yes, it may look scary to newcomers to D but the template
constraint is just for improved usability.
It also looks scary to me and I use D now for quite a while.
Assume I have this client code:
string[int] q;
byte[short] r;
q.update (r);
It produces this error message from your version:
$ dmd -checkaction=context -unittest -run v1
v1.d(21): Error: template `v1.update` cannot deduce function
from argument types `!()(string[int], byte[short])`
v1.d(3): Candidate is: `update(Target, From)(ref Target
target, From from)`
with `Target = string[int],
From = byte[short]`
must satisfy the following constraint:
` isImplicitlyConvertible!(ValueType!From,
ValueType!Target)`
If I remove the constraint (the if-stuff) I get
v1.d(12): Error: cannot implicitly convert expression
`kv.value()` of type `byte` to `string`
v1.d(23): Error: template instance `v1.update!(string[int],
byte[short])` error instantiating
Can this really be improved?
Stefan