在D中传递带泛型参数的函数指针

时间:2014-07-18 01:31:39

标签: casting function-pointers d void-pointers

我试图创建一个"每个"的实现。数组的方法。我希望能够像这样使用它:

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) is not callable using argument types (int[], void function(int* x))

我是以错误的方式解决这个问题,还是我错过了什么?

1 个答案:

答案 0 :(得分:3)

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; });
}

我目前无法检查这是否正确编译,但它应该会给你一个想法。

相关问题