这个错误是因为在调用 opApply 时,传递给委托的参数类型不匹配。在 foreach 中,kv 被声明为引用,因此在调用委托时,需要使用相应的引用类型。但是,在 opApply 的声明中,委托的参数类型是 ref Kref V,这意味着我们需要传递一个引用类型的参数。因此,我们需要对 opApply 的声明进行修改,以接受 const Kconst V 类型的参数:

int opApply(int delegate(ref const K, ref V) dg)
{
    int result;
    foreach (k, ref v; data) {
        result = dg(k, v);
        if (result) break;
    }
    return result;
}

int opApply(int delegate(ref const V) dg)
{
    int result;
    foreach (ref v; data.values) {
        result = dg(v);
        if (result) break;
    }
    return result;
}

int opApply(int delegate(ref const K) dg)
{
    int result;
    foreach (ref k; data.keys) {
        result = dg(k);
        if (result) break;
    }
    return result;
}

这样,我们就可以正确地使用 foreach 遍历 MyMap 对象了。

Dlang 编译错误: delegate `dg(ref string, ref int)` is not callable using argument types `(const(string), int)`

原文地址: https://www.cveoy.top/t/topic/olU1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录