当我们声明额外的模板参数而未在定义中使用时,为什么编译器会丢弃错误

Why does compiler throw an error when we declare an extra template argument and not used in definition?

本文关键字:为什么 编译器 错误 定义 声明 我们 参数      更新时间:2023-10-16

我有一个以下代码。

#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类,则汇编将成功。但是我想知道为什么编译器会打扰未使用的参数?

对于一般情况,编译器可以从:

中确定模板参数
  1. 用于调用函数的参数。
  2. 明确使用的类型来调用函数调用。

在您的情况下,由于参数未使用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;
}

编译器无法确定未使用模板参数的类型。您需要明确指定它,或删除未使用的模板参数。

相关文章: