小编min*_*nus的帖子

函数指针和模板

为什么以下代码有效?

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中编译和运行的

c++ templates visual-c++

4
推荐指数
1
解决办法
2376
查看次数

标签 统计

c++ ×1

templates ×1

visual-c++ ×1