在以下带有参数包和 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;
}
最佳答案
归功于 Xeo。
将参数放在参数包之后是强制推导的一种特殊情况。您不能显式地为 ReturnType
提供参数.因此它会寻找 foo1( int, int, int, int )
却一无所获。
顺便说一下,如果你想打败演绎,一个技巧是通过获取函数地址来隐藏参数列表:(&make_function<int,int,int,int>)(foo1)
.这导致 Clang 专门提示
candidate template ignored: couldn't infer template argument 'ReturnType'
它 ICE GCC(但仍然打印指向正确行的诊断)。
关于c++:为什么在提供模板函数的所有类型参数时出现错误,但在省略参数时正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21744659/