Consider the following program.
#include <iostream>
template <typename T>
void f( void ( *fn )( T ) )
{
fn( 42 );
}
void g( int x )
{
std::cout << "g( " << x << " );\n";
}
int main()
{
f( g );
}
The program compiles successfully and its output is
g( 42 );
Now let's rename the non-template function g
to f
.
#include <iostream>
template <typename T>
void f( void ( *fn )( T ) )
{
fn( 42 );
}
void f( int x )
{
std::cout << "f( " << x << " );\n";
}
int main()
{
f( f );
}
Now the program is not compiled by gcc HEAD 10.0.0 20200 and clang HEAD 10.0.0 but compiled successfully by Visual C++ 2019..
For example the compiler gcc issues the following set of messages.
prog.cc: In function 'int main()':
prog.cc:22:10: error: no matching function for call to 'f(<unresolved overloaded function type>)'
22 | f( f );
| ^
prog.cc:4:6: note: candidate: 'template<class T> void f(void (*)(T))'
4 | void f( void ( *fn )( T ) )
| ^
prog.cc:4:6: note: template argument deduction/substitution failed:
prog.cc:22:10: note: couldn't deduce template parameter 'T'
22 | f( f );
| ^
prog.cc:14:6: note: candidate: 'void f(int)'
14 | void f( int x )
| ^
prog.cc:14:13: note: no known conversion for argument 1 from '<unresolved overloaded function type>' to 'int'
14 | void f( int x )
| ~~~~^
So a question arises: should the code be compiled and what is the reason that the code is not compiled by gcc and clang?
It would seem to me that gcc and clang are correct. This should not compile. The function parameter from which you'd like T
to be deduced becomes a non-deduced context here the moment the argument supplied is an overload set that contains a function template [temp.deduct.type]/5.5:
The non-deduced contexts are:
- […]
A function parameter for which argument deduction cannot be done because the associated function argument is a function, or a set of overloaded functions ([over.over]), and one or more of the following apply:
- […]
- the set of functions supplied as an argument contains one or more function templates.
- […]
Thus, T
cannot be deduced and the other overload is not viable due to there being no conversion; exactly what gcc says…