模板实参推断(Template argument deduction)
函数模板(Function template) 和 类模板(Class template)
1.函数模板
类型实参的类型转换受限,一般而论,不会转换实参以匹配已有的实例化,相反,会产生新的实例。除了产生新的实例化之外,编译器只会执行两种转换。
View Code
1 template <typename T> T fobj(T, T); //arguments are copied 2 3 template <typename T> 4 T fref(const T&, const T&); //reference arguments 5 6 string s1("a value"); 7 const string s2("another value"); 8 9 fobj(s1,s2); //ok: calls f(string, string), const is ignored 10 11 fref(s1, s2); //ok: non const object s1 converted to const reference as the below 1) const conversions. 12 13 int a[10], b[42]; 14 fobj(a, b); //ok: calls f(int*, int*) 15 fref(a,b); //error: array types don't match: arguments aren't converted to pointers
1)const 转换:
-
接受 const 引用或 const 指针的函数可以分别用非 const 对象的引用或指针来调用,无须产生新的实例化
2)数组或函数到指针的转换
-
如果模板形参不是引用类型,则对数组或函数类型的实参应用常规指针转换
1 //模板实参推断 2 template<typename T> 3 int compare(const T& v1, const T& v2) 4 { 5 if(v1<v2) return -1; 6 if(v2<v1) return 1; 7 return 0; 8 } 9 10 int main() 11 { 12 short si; 13 // error: cannot instantiate compare(short, int) 14 // must be: compare(short, short) or 15 // compare(int, int) 16 17 compare (si, 1024); 18 return 0; 19 }
得出结论:函数模板的类型形参必须完全匹配。
2.类模板
当使用类模板成员函数,调用类模板成员函数比调用类似函数模板更灵活。用模板形参定义的函数形参的实参允许进行常规转换。
1 template<typename T> 2 class CTest 3 { 4 public: 5 int compare(const T& v1, const T& v2) 6 { 7 if(v1<v2) return -1; 8 if(v2<v1) return 1; 9 return 0; 10 } 11 }; 12 int main() 13 { 14 short si = 1; 15 16 17 CTest<int> cA; 18 cA.compare(si, 1024); 19 //ok: si converted to int and passed to compare 20 // instantiates CTest<int>::compare( const int&, const int& ) 21 return 0; 22 }

浙公网安备 33010602011771号