c++:为什么我在给出模板函数的所有类型参数时都会出错,而在省略参数时还好

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

本文关键字:出错 参数 类型参数 为什么 函数 c++      更新时间:2023-10-16

在下面的带有参数包和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特别抱怨

忽略候选模板:无法推断模板参数"ReturnType">

并且它ICEs GCC(但仍然打印指向右侧行的诊断)。