---
title: "C++ template"
author: "hcmfys"
date: "2009-09-24T10:25:00Z"
tags: ["C", "C#", "C++", "J#"]
slug: "c-template"
draft: false
lastmod: "2009-09-24T10:25:00Z"
id: 588787
url: "https://hcmfys.iteye.com/blog/588787"
---

```
#include <iostream>

using namespace std;
```

```


template <class T> 
inline T Max(T a, T b)
{
    return a > b ? a : b;
}

int main()
{
    int a = 1, b = 2;

    
```

```
    cout << Max(a, b) << endl;
    cout << Max(1.0, 2.0) << endl;
    cout << Max("hello", "world") << endl;

    
```

```
    return 0;
}
```

2.类模板

`#include <iostream> using namespace std; template <class T> class A { private:     T a; public:     A(T x) { a = x; }     T get() { return a; } }; int main() {     A<double> a(10);     cout << a.get() << endl;     return 0; }`

3.模板特殊化：当你在使用一个模板，而又想对某一个特殊的类型做不同的实现时，就需要一个特殊化的模板声明。

`// template specialization #include <iostream> using namespace std; // class template: template <class T> class specTemplate {     T m_var; public:     specTemplate (T inData) { m_var = inData; }     T increase () { return ++m_var; } }; // class template specialization: template <> class specTemplate <char> {     char m_var; public:     specTemplate (char arg) { m_var = arg; }     char upperCase ()     {         if ((m_var >= 'a') && (m_var <= 'z'))             m_var += 'A'-'a';         return m_var;     } }; int main () {     specTemplate<int> myint (7);     specTemplate<char> mychar ('j');     cout << myint.increase() << endl;     cout << mychar.upperCase() << endl;          return 0; }`

4.模板默认值：

`template <class T = char, int N = 10> class Test {..};`

1)模板的类型也可有默认值；

2)模板的类型也可以是regular type，并非一定是以class或typename修饰的类型；