Question

Somewhat related to Syntax of C++ templates with function type parameters but couldn't get rid of all my doubts there.

What is, if any, the difference between

template <void F(int)> 
void fun1 (int a) {F(a);}

and

template <void (*F)(int)> 
void fun2 (int a) {F(a);}

?

I tried instantiating both with something like

void called (int arg)
{
 ...
}

int main()
{
   fun1(10);
   fun2(20);
   return 0;
}

And looking at the generated assembly code from both clang 3.4 and gcc-4.8 (-O0 for both) I couldn't see any difference.

I know that the name of a function decays to a pointer to its type when passed as an argument, but couldn't find a clear explanation of what happens when it is used during a template instantiation as above. I'd say the "F" in the first template is the type of "something" that can be called with an argument of int and returns nothing, while "F" in the second template is a pointer to such a "something", and that in both implementations F can be used in the same way as it is the case when using a function name both directly and through a function pointer. I think this is strictly related to how function names decay into pointers, but I'm a bit confused as to what part of the standard formalizes this.

Was it helpful?

Solution

A non-type template-parameter of type “array of T” or “function returning T” is adjusted to be of type “pointer to T” or “pointer to function returning T”, respectively.

[C++ 11 standard, section 14.1 [temp.param], paragraph 8]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top