min*_*nus 4 c++ templates visual-c++
为什么以下代码有效?
class foo {
public:
template <typename F>
int Map(F function) const {
return function(2);
}
};
int Double(int n) {
return 2*n;
}
int main(){
foo f;
int n = f.Map(Double);
}
Run Code Online (Sandbox Code Playgroud)
我的理解是接受函数指针的函数必须具有如下格式:
void foo(int (*ptf)(int))
所以Map函数看起来应该是这样的
int Map(int (*ptf)(int)){
return (*ptf)(2);
}
Run Code Online (Sandbox Code Playgroud)
它是以某种方式在运行时或在编译时通过模板解析函数?上面的代码是在vc ++ 2010中编译和运行的
模板是一个编译时的概念,所以当然它会在编译期间解决(如果你的意思是模板参数替换).尝试传递一些你不能称之为的东西function(2),例如一些东西int.这将产生编译时错误.替换后,您的功能将如下所示
int Map(int (*function)(int)){
return function(2);
}
Run Code Online (Sandbox Code Playgroud)
你不明确需要取消引用函数指针,因为两者function(2)并(*function)(2)都立刻转化为所谓的功能标志.这本身又是提领,你可以建立一个循环链:(***********function)(2)仍然会工作,仍然是一样的function(2)和(*function)(2).
| 归档时间: |
|
| 查看次数: |
2376 次 |
| 最近记录: |