模板是泛型编程的基础,泛型编程即以一种独立于任何特定类型的方式编写代码。模板分为函数模板和类模板
模板函数
函数模板的定义如下:
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
|
#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
|
#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
|