在下面的代碼中,模板和函式都比較兩個字串并回傳哪個更大。然而,盡管代碼相同(定義體),結果卻不同。現在,它可能與獲取字串與字串有關(它是 C 錯誤嗎?) - 但是為什么模板有區別呢?
#include <iostream>
#include <string>
std::string getBiggerStr(std::string a, std::string b);
template <class T>
T getBigger(T a, T b);
int main() {
std::cout << "\t" << getBiggerStr("Amber", "John") << std::endl;
std::cout << "\t" << getBigger("Amber", "John") << std::endl;
return 0;
}
std::string getBiggerStr(std::string a, std::string b) {
if(a > b) return a;
return b;
}
template <class T>
T getBigger(T a, T b) {
if(a > b) return a;
return b;
}
結果:
John
Amber
為什么不一樣?模板定義體是從函式中復制粘貼的!
uj5u.com熱心網友回復:
getBigger("Amber", "John")呼叫getBigger<const char*>回傳哪個記憶體地址是更高的數字。
uj5u.com熱心網友回復:
getBigger("Amber", "John")函式呼叫中的實參(以及模板形參)的型別是const char*. 因此,該函式中的比較僅比較兩個指標,這不是正確比較(按字典順序)兩個 C 樣式字串的方法。
為了強制使用std::string作為引數/模板型別,您可以將operator ""s后綴附加到文字:
using namespace std::string_literals;
int main() {
std::cout << "\t" << getBiggerStr("Amber", "John") << std::endl; // Automatic conversion to std::string
std::cout << "\t" << getBigger("Amber"s, "John"s) << std::endl; // Here, we need to explicitly specify
return 0;
}
或者,如果您沒有符合 C 14 的編譯器( 需要operator ""s),那么您可以顯式構造兩個std::string物件作為引數:
std::cout << "\t" << getBigger(std::string{ "Amber" }, std::string{ "John" }) << std::endl;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/472984.html
上一篇:CGAL:填孔.exe檔案卡住
下一篇:如何啟動多個結構
