在定义ByKeyValueRange结构体时,需要将const(Person)* p改为const ref Person p,表示传入一个Person类型的常量引用,而不是指向常量的指针。修改后的代码如下:

struct ByKeyValueRange { string[] keys = ["age", "name"]; const ref Person p; size_t index;

bool empty() const pure @safe {
    return index >= keys.length;
}

void popFront() @safe {
    ++index;
}

auto front() const @safe {
    return Entry(keys[index], &p);
}

}

同时,在Entry结构体的构造函数中,也需要将const(Person)* p改为const ref Person p。修改后的代码如下:

struct Entry { string key; const ref Person p;

this(string key, const ref Person p)
{
    this.key = key;
    this.p = p;
}

@property
string val() const @safe {
    return getFieldAsString(&p, key);
}
dlang语言以下代码报错提示f_range_forach自定义遍历d43 Error cannot implicitly convert expression &this of type constPerson to string代码如下import stdstdio;import stdconvto;import stdalgorithm;struct Person int age;

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

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