当我们声明额外的模板参数而未在定义中使用时,为什么编译器会丢弃错误
Why does compiler throw an error when we declare an extra template argument and not used in definition?
我有一个以下代码。
#include <iostream>
template <class T,class U>
T myMax(T x, T y)
{
return (x > y)? x: y;
}
int main()
{
std::cout << myMax(3, 7) << std::endl; // Call myMax for int
std::cout << myMax(3.0, 7.0) << std::endl; // call myMax for double
std::cout << myMax('g', 'e') << std::endl; // call myMax for char
return 0;
}
在编译代码时,编译器报告了一个错误,如下所示。
functionTemplates.cpp: In function ‘int main()’:
functionTemplates.cpp:18: error: no matching function for call to ‘myMax(int, int)’
functionTemplates.cpp:19: error: no matching function for call to ‘myMax(double, double)’
functionTemplates.cpp:20: error: no matching function for call to ‘myMax(char, char)’
我知道,如果我删除U类,则汇编将成功。但是我想知道为什么编译器会打扰未使用的参数?
对于一般情况,编译器可以从:
中确定模板参数- 用于调用函数的参数。
- 明确使用的类型来调用函数调用。
在您的情况下,由于参数未使用U
,因此无法从用于进行函数调用的参数中确定U
。编译器可以确定U
的唯一其他方式是在函数调用中明确使用它。例如
std::cout << myMax<int, double>(3, 7) << std::endl;
PS 我不清楚为什么您首先将U
作为模板参数。它根本不使用。不会更容易使用:
template <class T>
T myMax(T x, T y)
{
return (x > y)? x: y;
}
编译器无法确定未使用模板参数的类型。您需要明确指定它,或删除未使用的模板参数。
相关文章:
- 为什么C++编译器没有检测到正确声明的类?
- 为什么编译器将其解析为函数指针而不是递归调用?
- 为什么编译器说"candidate template ignored: couldn't infer template argument 'InputIterator'"?
- 为什么编译器不检查被覆盖函数的存储类?
- 为什么编译器在使用"无常量复制构造函数"时抱怨?
- 为什么编译器接受具有长双精度文本的浮点数的初始化?
- 为什么编译器抱怨 std::thread 参数在转换为右值后必须是可调用的?
- 为什么编译器C++不能知道指针指向派生类?
- 为什么C++编译器不能做更好的常量折叠?
- 如果函数包含静态变量,为什么编译器不执行内联?
- 为什么 C++ 编译器在"c:program filesgnu emacsinclude"中查找包含文件?
- 为什么C++编译器无法内联传递给函数模板的lambda
- 从 std::ostream 重载 << 运算符时,为什么编译器会给出"too many parameters for this operator function"错误?
- 为什么 C 编译器不在 for 循环体中给出重新声明错误?
- 为什么编译器不在同一翻译单元中警告 ODR 违规
- 如果类在 C++ 中具有常量或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?
- 为什么编译器使用移动构造函数而不是复制构造函数
- 为什么编译器无法弄清楚构造函数实际上是 constexpr?
- x86 - 为什么编译器在下一条指令中插入看似毫无意义的JMP?
- 为什么编译器不能优化这个 std::string 构造?