Dlang 编译错误:`map.opApply` 匹配多个声明,无法推断参数类型
该错误是因为在 MyMap 类中定义了三个 opApply 函数,它们的参数类型不同,但是函数名相同。在代码中使用 foreach 遍历时,编译器无法确定应该调用哪个 opApply 函数。
解决方法是为每个 opApply 函数添加不同的函数名,例如:
int opApplyKeyValue(int delegate(ref const K, ref V) dg)
{
// ...
}
int opApplyValue(int delegate(ref const V) dg)
{
// ...
}
int opApplyKey(int delegate(ref const K) dg)
{
// ...
}
然后在使用 foreach 遍历时,分别调用对应的函数名即可。例如:
foreach (key, value; map.opApplyKeyValue) {
writeln(key, ': ', value);
}
foreach (key; map.opApplyKey) {
writeln(key);
}
foreach (value; map.opApplyValue) {
writeln(value);
}
代码如下:
import std.stdio;
class MyMap(K, V)
{
private {
V[K] data;
}
public {
void insert(K key, V value)
{
data[key] = value;
}
V get(K key)
{
return data[key];
}
int opApplyKeyValue(int delegate(ref const K, ref V) dg)
{
int result;
foreach (ref k, ref v; data) {
result = dg(k, v);
if (result) break;
}
return result;
}
int opApplyValue(int delegate(ref const V) dg)
{
int result;
foreach (ref v; data.values) {
result = dg(v);
if (result) break;
}
return result;
}
int opApplyKey(int delegate(ref const K) dg)
{
int result;
foreach (ref k; data.keys) {
result = dg(k);
if (result) break;
}
return result;
}
}
}
void main()
{
auto map = new MyMap!(string,int)();
map.insert('one', 1);
map.insert('two', 2);
map.insert('three', 3);
// 遍历键值对
foreach (key, value; map.opApplyKeyValue) {
writeln(key, ': ', value);
}
// 遍历键
foreach (key; map.opApplyKey) {
writeln(key);
}
// 遍历值
foreach (value; map.opApplyValue) {
writeln(value);
}
}
原文地址: https://www.cveoy.top/t/topic/olU5 著作权归作者所有。请勿转载和采集!