template <typename T> void func(T&){ } int main(){ void (*p)(int&) = func;//or &func return 0; }
I wonder why this code compiles (with g++). It seems the argument of template function is deduced from the type of p? Is this standard behavior?
Edit: I came up with a possible explanation. That assignment has signature:
void(*&)(int&)operator=(void(*)(int&));
So func is actually deduced from the input argument type of operator=, rather than from type of p directly. Is that correct?
Template argument deduction is used when selecting user-defined conversion function template arguments. A is the type that is required as the result of the conversion. P is the return type of the conversion function template.
A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
Type inference or deduction refers to the automatic detection of the data type of an expression in a programming language. It is a feature present in some strongly statically typed languages. In C++, the auto keyword(added in C++ 11) is used for automatic type deduction.
Is this standard behavior?
Yes it is. Template argument deduction also happens when you take the address of a function template (such as you do when assigning to or initializing a function pointer). It's explicitly allowed in [temp.deduct.funcaddr]/1:
Template arguments can be deduced from the type specified when taking the address of an overloaded function. The function template's function type and the specified type are used as the types of P and A, and the deduction is done as described in [temp.deduct.type].
The function pointer type provides the argument (A
in the above paragraph).
So func is actually deduced from the input argument type of operator=, rather than from type of p directly. Is that correct?
Not really. For one, it's not assignment, it's initialization that you are doing. And even if it was using an overloaded operator=
function, you'd need deduction to initialize the argument for the assignment operator, which brings you back to square one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With