模板

模板是泛型编程的基础,泛型编程即以一种独立于任何特定类型的方式编写代码。模板分为函数模板和类模板

模板函数

函数模板的定义如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
template <typename T>
返回类型 函数名(形参表)
*/
#include <iostream>
using std::cout;
using std::endl;

//交换两个参数的值
template <typename T>
void swap(T &a, T &b)
{
T tmp;
tmp = a;
a = b;
b = tmp;
}

int main()
{
int a = 1, b = 2;
char d = 'D', e = 'E';
swap(a, b);
swap(d, e);
cout << "a: " << a << " b: " << b << endl;
cout << "d: " << d << " e: " << e << endl;
return 0;
}

类模板

可以像函数模板一样创建类模板,创建方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
template <typename T>
class name {

}
*/

//有问题的单例类模板仅作格式参考
#ifndef SINGLETON_H
#define SINGLETON_H

#include <memory>
#include <mutex>

template <typename T>
class singleton
{
public:
template <typename... Args>
static T* get_instance(Args&&... args)
{
if (!s_instance)
{
std::lock_guard<std::mutex> lck(s_instance_mtx);
if (!s_instance)
{
s_instance = std::shared_ptr<T>(new T(std::forward<Args>(args)...));
}
}
return s_instance.get();
}

static void release_instance()
{
if (s_instance)
{
std::lock_guard<std::mutex> lck(s_instance_mtx);
if (s_instance)
{
s_instance.reset();
}
}
}

private:
static std::shared_ptr<T> s_instance;
static std::mutex s_instance_mtx;
};

template <typename T>
std::mutex singleton<T>::s_instance_mtx;

template <typename T>
std::shared_ptr<T> singleton<T>::s_instance;

#endif /* SINGLETON_H */

模板
https://carl-5535.github.io/2022/03/27/C++/模板/
作者
Carl Chen
发布于
2022年3月27日
许可协议