簡體   English   中英

當我們聲明一個額外的模板參數而不在定義中使用時,為什么編譯器會拋出錯誤?

[英]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類,編譯將成功。 但是我想知道為什么編譯器會為一個未使用的參數煩惱?

編譯器無法確定未使用的模板參數的類型。 您需要明確指定它,或刪除未使用的模板參數。

對於一般情況,編譯器可以從以下命令確定模板參數:

  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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM