c++:为什么我在给出模板函数的所有类型参数时都会出错,而在省略参数时还好
c++: why am I getting an error when giving all type parameters of a template function, but OK when omitting a parameter?
在下面的带有参数包和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(但仍然打印指向右侧行的诊断)。
相关文章:
- 为 NewObjectA() 函数创建 jvalues 的参数数组时出错 - JNI Invocation API
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 使用一个参数的模板函数时出错(适用于 2)
- 为什么在函数参数前面添加 const 会出错?
- 变量用作C中的函数参数后出错
- 将私有数据成员作为默认参数传递给该类的公共方法时出错
- 使用 cvThreshold 时报告参数时出错
- STL 容器在函数中作为模板参数,在调用中出错
- 使用模板模板参数时出错
- 方法的参数列表出错
- 将 std::bind 应用于带有参数 <boost::asio::ip::tcp::socket> 时出错?
- 使用模板函数传递模板参数时出错
- 在 c++ 中调用将字符串作为参数传递的函数时出错
- 在运算符中将联合作为参数传递时出错<<
- 在C 中使用Caffe;无法将Caffe ::求解参数仪发挥作用而不会出错
- 尝试使用浮点参数运行重载函数时出错
- C++ 在C++中通过引用将枚举作为默认参数传递时出错
- C++输入重定向导致文件参数工作时出错
- 将非静态函数作为参数传递时出错
- Win32 窗口包装器出错(参数不正确)