In the following template function with a parameter pack and a ReturnType
, why is the compiler OK if I omit the last parameter ReturnType
, whereas giving me an error (about ambiguity) if I explicitly give the the last type parameter.
Thanks.
#include <functional>
using namespace std;
template<typename... Args, typename ReturnType>
auto make_function(ReturnType(*p)(Args...))
-> std::function<ReturnType(Args...)> {
return {p};
}
int foo1(int x, int y, int z) { return x + y + z;}
float foo1(int x, int y, float z) { return x + y + z;}
int main() {
auto f0 = make_function<int,int,int>(foo1); //OK
//auto f1 = make_function<int,int,int,int>(foo1); //not OK
// test33.cpp:15:48: error: no matching function for call to
// 'make_function(<unresolved overloaded function type>)'
return 0;
}
Credit to Xeo.
Putting a parameter after a parameter pack is a special case where deduction is forced. You cannot explicitly supply an argument to ReturnType
. Therefore it goes looking for foo1( int, int, int, int )
and finds nothing.
By the way, if you want to defeat deduction, one trick is to hide the argument list by taking the address of the function: (&make_function<int,int,int,int>)(foo1)
. This causes Clang to complain specifically
candidate template ignored: couldn't infer template argument 'ReturnType'
and it ICEs GCC (but still prints a diagnostic pointing to the right line).
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