This code snippet fails to compile in MSVC, Clang and Gcc, (they give different error message):
int foo(int a, int b) {
return a + b;
}
template <class Ret, class A, class B>
void foo(Ret (*)(A, B)) {
}
int main() {
foo(foo);
return 0;
}
Shouldn't this compile? I can't see why it fails in resolving the overloaded function or in deducing the template arguments. Any help is welcome, thanks.
PS: It compiles if the template is replaced with void foo(int (*)(int, int))
, or if we rename one of foo
to avoid overloading.
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 function can be overloaded either by a non-template function or using an ordinary function template.
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.
The process of selecting the most appropriate overloaded function or operator is called overload resolution. Suppose that f is an overloaded function name. When you call the overloaded function f() , the compiler creates a set of candidate functions.
For simplicity, let's call the first overload foo1
and call the second overload foo2
.
With templates, the problem is that you cannot deduce the template arguments for the outer foo
, according to [temp.deduct.call]/6:
If the argument is an overload set containing one or more function templates, the parameter is treated as a non-deduced context.
Without templates, the program considers all possibilities foo1(foo1)
, foo1(foo2)
, foo2(foo1)
, foo2(foo2)
and chooses the only viable one foo2(foo1)
, according to [over.over]/6:
[ Note: If
f()
andg()
are both overloaded functions, the cross product of possibilities must be considered to resolvef(&g)
, or the equivalent expressionf(g)
. — end note ]
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