Dlang 语言自定义遍历错误解决:f_range_forach 无法隐式转换 const(Person)* 为 string[]
在定义 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);
}
}
通过以上修改,就可以解决 f_range_forach 无法隐式转换 const(Person)* 为 string[] 的错误。
原文地址: https://www.cveoy.top/t/topic/olTT 著作权归作者所有。请勿转载和采集!