[计算机科学经

1 deduction process 11 167 template argument

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: e <typename T> inline T const& max (T const& a, T const& b) { return a < b ? b : a; } int main() { std::string s; ::max("apple","peach"); ::max("apple","tomato"); ::max("apple",s); // OK:型別相同 // ERROR:型別不同 // ERROR:型別不同 } 問題出在這幾個字串字面常數(string literals)的長度不同,因而其底層的 array 型別也不同。 換句話說 "apple" 和 "peach" 的 array 型別都是 char const[6],而 "tomato" 的 array 型 別是 char const[7]。㆖述呼叫只有第㆒個合法,因為兩個參數具有相同型別;然而如果你使 用 by value 傳遞方式,就可以傳遞不同型別的字串字面常數(string literals),其對應的 array 大小不同: // basics/max6.hpp #include <string> // 注意:使用 non-reference parameters template <typename T> inline T max(T a, T b) { return a < b ? b : a; } C++ Templates - The Complete Guide 5 58 高階基本技術 int main() { std::string s; ::max...
View Full Document

This note was uploaded on 08/25/2012 for the course EECS 101 taught by Professor Wre during the Fall '12 term at Beacon FL.

Ask a homework question - tutors are online