目录
- #include
- using namespace std;
- template<class T,size_t N>
- class Stack
- {
- private:
- T _a[N];
- };
- int main()
- {
- Stack<int, 10>s1;
- Stack<double, 1000>s2;
- cout << sizeof(s1) / sizeof(int) << endl;//10
- cout << sizeof(s2) / sizeof(double);//1000
- return 0;
- }

- // 通用模板函数
- template <typename T>
- bool isGreater(T a, T b)
- {
- return a > b;
- }
-
- // 特化版本针对字符类型
- template <>
- bool isGreater<char>(char a, char b)
- {
- cout << "Using specialized version for characters." << endl;
- return toupper(a) > toupper(b);
- }
- #include
- #include
- using namespace std;
- // 通用模板函数
- template <typename T>
- bool isGreater(T a, T b) {
- return a > b;
- }
-
- // 特化版本针对字符类型
- template <>
- bool isGreater<char>(char a, char b) {
- cout << "Using specialized version for characters." << endl;
- return toupper(a) > toupper(b);
- }
-
- int main()
- {
- if (isGreater(69, 66))
- {
- cout << "69 is greater than 66" << endl;
- }
- else
- {
- cout << "69 is not greater than 66" << endl;
- }
-
- if (isGreater('G', 'B'))
- {
- cout << "G is greater than B" << endl;
- }
- else
- {
- cout << "G is not greater than B" << endl;
- }
- return 0;
- }
- #include
- using namespace std;
- template<class T1, class T2>
- class Data
- {
- public:
- Data()
- {
- cout << "Data
" << endl; - }
- private:
- T1 _d1;
- T2 _d2;
- };
-
- template<>
- class Data<int, char>
- {
- public:
- Data()
- {
- cout << "Data
" << endl; - }
- private:
- int _d1;
- char _d2;
- };
-
- int main()
- {
- Data<int, int> d1;
- Data<int, char> d2;
- return 0;
- }
- // 将第二个参数特化为int
- template <class T1>
- class Data
int> - {
- public:
- Data() { cout << "Data
" << endl; } - private:
- T1 _d1;
- int _d2;
- };
- //两个参数偏特化为指针类型
- template <typename T1, typename T2>
- class Data
- {
- public:
- Data()
- {
- cout << "Data
" << endl; - }
- private:
- T1 _d1;
- T2 _d2;
- };
- //两个参数偏特化为引用类型
- template <typename T1, typename T2>
- class Data
- {
- public:
- Data(const T1& d1, const T2& d2)
- : _d1(d1)
- , _d2(d2)
- {
- cout << "Data
" << endl; - }
- private:
- const T1& _d1;
- const T2& _d2;
- };
- #include
- using namespace std;
-
- template<class T1, class T2>
- class Data
- {
- public:
- Data()
- {
- cout << "Data
" << endl; - }
- private:
- T1 _d1;
- T2 _d2;
- };
-
- template <typename T1, typename T2>
- class Data
- {
- public:
- Data()
- {
- cout << "Data
" << endl; - }
- private:
- T1* _d1;
- T2* _d2;
- };
-
- template <typename T1, typename T2>
- class Data
- {
- public:
- Data(const T1& d1, const T2& d2)
- : _d1(d1)
- , _d2(d2)
- {
- cout << "Data
" << endl; - }
- private:
- const T1& _d1;
- const T2& _d2;
- };
-
- int main()
- {
- Data<int, char>d;
- Data<int*, int*> d1;
- Data<const int&, const int&> d2(5, 10); // 提供初始化值
- return 0;
- }
