簡體   English   中英

模板功能-類型檢查錯誤-C ++

[英]template function - type checking error - c++

我有這個功能模板

template < class TParam >
bool greaterThan (TParam A, TParam B) {
  if (typeid(TParam) == typeid(string)) {   
    return A.compare(B) > 0;   <--------------- Error
  } else {
    return A > B;
  }
}

但是編譯器不允許我將它與int一起使用。

我在上面顯示的位置收到編譯器錯誤,內容為

Member reference base type 'int' is not a structure or union.

如果我在int上調用函數,則if語句不會運行。

我將其注釋掉並進行了檢查。 我不知道怎么了

TParamint時:

A.compare(B)

您正在嘗試調用intcompare方法。 這種方法不存在。 您需要的是模板專門化,以便您可以在類型為特定類型時使模板做一些特殊的事情:

template<class TParam>
bool greaterThan(TParam A, TParam B) {
    return A > B; // this will be called for any type except string because of
                  // our following specialisation
}

// make a specialisation for when the template parameter is string
template<>
bool greaterThan<string>(string A, string B) { 
   return A.compare(B) > 0;
}

語法有點陌生,但是如果您仔細閱讀一下,模板專業化是模板的強大功能。

請注意, string確實具有operator<因此,如果您不需要,甚至不需要對其進行特殊化,但這是學習模板特殊化的好機會。

您知道您不是在int上調用compare ,但是編譯器不會:您的if在運行時求值。

由於string是模板中唯一的特殊情況,請嘗試以下操作:

template < class TParam >
bool greaterThan (TParam A, TParam B) {
    return A > B;
}
bool greaterThan(const string& a, const string& b) {
    return a.compare(b) > 0;
}

模板代碼在編譯時生成,因此if()語句尚未執行。

有2種解決方案

a)為int提供專門的模板版本

b)不要使用Compare()-並要求結構/類提供比較運算符。

調用模板函數會使編譯器實例化整個函數,而導致錯誤的語句顯然不適用於int參數。 有兩種方法可以區分這兩種情況:

首先,對字符串使用greaterThan特殊化

template < class TParam >
bool greaterThan (TParam A, TParam B) {
  return A > B;
}

template<>
bool greaterThan< string > (string A, string B) {
  return A.compare(B) > 0;
}

其次,對字符串使用greaterThan重載

template < class TParam >
bool greaterThan (TParam A, TParam B) {
  return A > B;
}

bool greaterThan (string const & A, string const & B) {
  return A.compare(B) > 0;
}

在這兩個選項中,要在編譯時決定調用哪個函數,而不是在運行時檢查類型。 但是請注意,重載通過引用接受參數,而專業化則通過接受參數,因為它必須與基本模板函數的簽名完全匹配。

同樣,通過專業化,編譯器選擇的功能有時可能是意外的。 而且由於功能模板只能被明確地專門化(即不能部分地專門化),所以重載提供了與專門化相關的所有優點,而沒有缺點。

有關更多信息,請參見Herb Sutter的“ 為什么不專門化功能模板? ”。

暫無
暫無

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

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