Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can C++ deduce template arguments on the right side of an assignment operator from the left side?

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?

like image 455
lowsfer Avatar asked Dec 22 '17 10:12

lowsfer


People also ask

What is template argument deduction?

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.

What is a template argument?

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.

What is type deduction C++?

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.


1 Answers

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.

like image 142
StoryTeller - Unslander Monica Avatar answered Sep 27 '22 18:09

StoryTeller - Unslander Monica