Templates are compiled twice:
-
Without instantiation, the template code itself is checked for correct syntax. Syntax errors are discovered, such as missing semicolons.
-
At the time of instantiation, the template code is checked to ensure that all calls are valid. Invalid calls are discovered, such as unsupported function calls.
Automatic type conversion is not considered for templates but is considered for ordinary functions.
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
max.hpp
1 template <typename T>
2 inline T const& max(T const& a, T const& b)
3 {
4 return a < b ? b : a;
5 }
6
7 inline const int& max(const int& a, const int& b)
8 {
9 return a < b ? b : a;
10 }
11
12 template<typename T>
13 inline T const& max(const T& a, const T& b, const T& c)
14 {
15 return max(max(a, b), c);
16 }
17
18 inline const char* const max(const char* const a, const char* const b)
19 {
20 return ::strcmp(a, b) < 0 ? b : a;
21 }
22
23 template<typename T>
24 inline T* const max(T* const a, T* const b)
25 {
26 return *a < *b ? b : a;
27 }
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
max.cpp
1 #include <iostream>
2 #include <string>
3 #include <cstring>
4 #include "max.hpp"
5 using namespace std;
6
7 int main()
8 {
9 int i = 42;
10 cout << "max(7, i):" << ::max(7, i) << endl;
11
12 double f1 = 3.4;
13 double f2 = -6.7;
14 cout << "max(f1, f2):" << ::max(f1, f2) << endl;
15
16 string s1 = "hello, sunshine";
17 string s2 = "hello, ray";
18 cout << "max(s1, s2):" << ::max(s1, s2) << endl;
19
20 cout << ::max<double>(1, 2.1) << endl;
21 cout << ::max<double>(static_cast<double>(1), 2.1) << endl;
22
23 cout << ::max(7, 42, 68) << endl;
24 cout << ::max(7.0, 42.0) << endl;
25 cout << ::max('a', 'b') << endl;
26 cout << ::max(7, 42) << endl;
27 cout << ::max<>(7, 42) << endl;
28 cout << ::max<double>(7, 42) << endl;
29 cout << ::max('a', 42.7) << endl;
30
31 int a = 7;
32 int b = 42;
33 cout << ::max<>(a, b) << endl;
34
35 string s = "hey";
36 string t = "you";
37 cout << ::max(s, t) << endl;
38
39 int* p1 = &b;
40 int* p2 = &a;
41 cout << *(::max(p1, p2)) << endl;
42
43 const char* cs1 = "ray";
44 const char* cs2 = "summer";
45 cout << ::max(cs1, cs2) << endl;
46
47 cin.get();
48 }