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

标签 casting function-pointers d void-pointers

我正在尝试为数组创建“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/

相关文章:

d - 使用inotify 为什么我的监视文件被忽略?

pipe - D 编程 - 如何从 stdin 获取管道内容

c++ - 将此 c-cast 更改为 reinterpret_cast 是否安全?

c - 在编译单元之间传递函数指针时有什么陷阱吗?

c - 夹板警告 "Statement has no effect"由于函数指针

c - 在 C 中的数组上实现通用 'map' 函数

eclipse - 尝试调试 D 程序时出错

c++ - 如何防止从 char 数组到 bool 的隐式转换

Java:必须转换为短,不能使用简写 'S'

android - 如何以编程方式将 Android 屏幕/应用程序镜像到屏幕?