简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM