Function Index and Template

Why does the following code work?

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

I understand that a function that takes a function pointer must have a format, for example:

void foo(int (*ptf)(int))

So the Map function should look like

 int Map(int (*ptf)(int)){ return (*ptf)(2); } 

Does it somehow allow the function at run time or at compile time through the template? the above code was compiled and run in vC ++ 2010

+4
source share
1 answer

A template is a concept of compilation time, so of course it will be allowed at compile time (if you mean replacing template parameters). Try passing something that you cannot name as function(2) , for example, some int . This will result in a compile time error. After substituting, your function will look like

 int Map(int (*function)(int)){ return function(2); } 

You obviously do not need to look for a pointer to a function, because both function(2) and (*function)(2) instantly converted to the so-called function notation. This in itself is wanted again, and you can build an endless chain: (***********function)(2) will still work and will still be the same as function(2) and (*function)(2) .

+5
source

All Articles