我正在尝试为数组创建“each”方法的实现。我希望能够像这样使用它:
void each(void*[] arr, void function(void*) f) {
assert(arr != null);
foreach(int i, void* x ; arr){
f(&x);
}
}
void setToFive(int* x){
*x = 5
}
int main(){
int[] arr = new int[50];
each(arr, &setToFive);
writeln(arr);
return 0;
}
但是,我收到错误:
function test.each (void*[] stuff, void function(void*) f) 无法使用参数类型 (int[], void function(int* x)) 进行调用
我是否以错误的方式解决这个问题,或者我错过了什么?
最佳答案
int[] 无法转换为 void* 数组。我建议使用模板。
void each(Type)(Type[] array, void delegate(ref Type) cb){
foreach(ref element; array)
cb(element);
}
void main(){
int[] arr = new int[50];
arr.each((e){ e += 5; });
}
我目前无法检查它是否可以正确编译,但它应该可以给您一个想法。
关于casting - 在 D 中传递带有泛型参数的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24816048/