3

作为一个编程练习,我决定尝试为我正在用 c++ 做的一门课程实现我所有的haskell 作业。目前,我正在尝试发送此功能:

int callme(){
    cout << "callme called" << endl;
    return 0;
}

到这个功能:

template<class type1,class type2> void callfunc(type1(*f)(type2)){
    (*f)(); 
}

用这个电话:

int main(){
    callfunc<int,void>(callme);
}

但我得到了错误:

macros.cc: In function ‘int main()’:
macros.cc:45:29: error: no matching function for call to ‘callfunc(int (&)())’

是什么赋予了?我能够以完全相同的方式发送一个函数作为参数,只是没有模板......唯一应该改变的是在编译之前将类型名称替换到它们的适当位置,不是吗?

4

1 回答 1

1

我认为'void'是c ++中的'特例'。编译器无法将 f() 与 f(void) 匹配,将其替换为任何其他类型,它将编译。对我来说,这只是另一个 c++ 魔法,但也许有人知道得更好。这将编译:

int callme(int){ printf("ok int\n"); return 0; }
int callme(char){ printf("ok char\n"); return 0; }
template<class type1,class type2> void callfunc(type1(*f)(type2), type2 p) {
  (*f)(p);
}

int main() {
  callfunc<int,int>(callme, 1);
  callfunc<int,char>(callme, 1);
}
于 2013-02-01T07:39:16.543 回答