1. 程式人生 > 其它 >CPP 如何將一個函式泛型化 How to Make a Function Generic

CPP 如何將一個函式泛型化 How to Make a Function Generic

1.  Developing generic function (設計泛型函式)

1.1. Steps (步驟)

(1)     To start with non-generic function  (先設計/編寫一個非泛型函式)

(2)     To debug and test it             (除錯/測試該函式)

(3)     To convert it to a generic function  (將上述非泛型函式轉換為泛型函式)

1.2. How to transform(如何泛型化)

(1)     What DATA does the function process? (函式處理哪些資料)

(2)     What are the TYPEs of the DATA?(資料的型別是什麼)

(3)     Transform the TYPEs to TYPE Parameters

2. 示例——Generic Sort Function (泛型排序函式)

2.1. 非泛型函式原型 

void selectionSort(double list[] , const int size);

2.2. 泛型函式原型

 將double轉成T:

template <typename T>

void selectionSort(T list[] , const int size);

注意:模板類的宣告和實現不能分離,即都在.h檔案中。

也有分離的方法,檢視:https://blog.csdn.net/weixin_40539125/article/details/83375452?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-83375452-blog-77689009.pc_relevant_recovery_v2&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-83375452-blog-77689009.pc_relevant_recovery_v2&utm_relevant_index=2