在下面带有参数包和a的模板函数中,ReturnType
如果我省略了最后一个参数,为什么编译器没问题ReturnType
,而如果我明确给出最后一个类型参数,则给我一个错误(关于歧义).
谢谢.
#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;
}
Run Code Online (Sandbox Code Playgroud)
感谢 Xeo。
将参数放在参数包之后是强制推导的特殊情况。您不能显式地向 提供参数ReturnType
。因此它去寻找foo1( int, int, int, int )
却一无所获。
顺便说一句,如果你想击败演绎,一个技巧是通过获取函数的地址来隐藏参数列表:(&make_function<int,int,int,int>)(foo1)
。这导致 Clang 专门抱怨
候选模板被忽略:无法推断模板参数“ReturnType”
它是 GCC 的 ICE(但仍然打印指向正确行的诊断信息)。