Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: why am I getting an error when giving all type parameters of a template function, but OK when omitting a parameter?

Tags:

c++

templates

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;
}
like image 298
thor Avatar asked Nov 11 '22 13:11

thor


1 Answers

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).

like image 148
Potatoswatter Avatar answered Nov 14 '22 22:11

Potatoswatter