# c++ template create : 2024/11/04 last update : 2024/12/06 ## 介紹 [【带你吃透C++】模板详解🎃 引入:泛型编程 泛型编程最初诞生于 C++ 中,由 Alexander Stepanov - 掘金](https://juejin.cn/post/7078530622527897631) template:用在class(或struct)和function(一般的function跟member func) 感覺:用在class的template主要用於data member跟專門用於class的成員函數 generic programming,對type做一般化(generalize)、參數化 template:給編譯器用的藍圖、模具 func template:一般化參數的type跟return的type function template顯式、隱式實例化:<> 想想:函數、類模板:編譯器怎麼做(類似class) class template:e.g.container list、deque... std::list\<int> my_list; ### 簡單例子 :::spoiler code ```cpp= #include <iostream> #include <string> // 需求:一個函數可以印出任意type的兩個變數的值,這兩個變數的type可相同也可不同 template<typename T1, typename T2> void Display(T1 var1, T2 var2) { std::cout << var1 << " " << var2 << std::endl; } int main() { std::string s = "Hellow"; int a = 3; float f = 1.2345; Display(f, s); // 想想這行編譯器做了啥事 Display<int, std::string>(a, s); // 想想這行編譯器做了啥事 Display<int, std::string>(f, s); // 想想這行編譯器做了啥事 return 0; } ``` ::: ## 顯式隱式實例化 不同東西的template的Implicit Instantiation由不同的c++標準支援,有些是不支援的。 為了可讀性以及支援性,最好都做Explicit Instantiation 補充:模板類跟模板函數要定義才能實例化。 ```cpp= #include <iostream> #include <vector> #include <memory> template <typename T> T FuncAdd(T num1, T num2) { T res = num1 + num2; return res; } int main() { std::vector<int> vec = {1, 2, 3}; // Explicit Instantiatio std::vector vec2 = {1, 2, 3}; // Implicit Instantiation of container : c++17 and later // std::vector<> vec3 = {1, 2, 3}; // error // std::unique_ptr up(new int(3)); //error std::unique_ptr<int> up2(new int(3)); float f1 = 1.1; float f2 = 2.2; std::cout << FuncAdd<float>(f1, f2) << std::endl; //Explicit Instantiation : better std::cout << FuncAdd<>(f1, f2) << std::endl; // Implicit Instantiation std::cout << FuncAdd(f1, f2) << std::endl; // Implicit Instantiation return 0; } ``` ## template defined on header [【带你吃透C++】模板详解🎃 引入:泛型编程 泛型编程最初诞生于 C++ 中,由 Alexander Stepanov - 掘金](https://juejin.cn/post/7078530622527897631) [模版定义一定要写在头文件中吗?_template 头文件-CSDN博客](https://blog.csdn.net/qq_29426201/article/details/123639212) template 定義常寫在header,也可不寫在header,但要想想方法/上網查查