======Generic And Template====== =====Generic คืออะไร===== คือการเขียนโปรแกรมให้สามารถใช้ได้กับหลากหลาย DataType โดยทั่วไปเรามักจะใช้ Generic กับการเขียนโปรแกรมดังนี้ * Generic Procedure/Function * Generic Class =====1. Generic Procedure/Function===== คือการสร้าง Procedure/Function ที่รับค่า(หรือส่งค่า) Argument โดยไม่ได้ระบุ DataType เพื่อให้ Procedure/Function ดังกล่าว สามารถนำไปใช้ได้กับ DataType ที่หลากหลายนั่นเอง \\ รูปแบบการประกาศ สรุปได้ดังนี้ ^ Topic ^ Format ^ |Generic Procedure| generic procedure ProcedureName(Arg1:T); begin {Do something} end; | |Generic Function| generic function FunctionName(Arg1:T):T; begin {Do something} end; | การเรียกใช้ สมตติว่าเราจะนำมาใช้กับ integer จะเรียกใช้ได้ดังนี้ specialize FunctionName(x): generic function sum(x,y:T):T; begin result:=x+y; end; var x,y:double; Begin x:=12.78; y:=9.86; writeln('sum(x,y) = ',specialize sum(x,y)); End. \\ **__หมายเหตุ__** - Generic Function ปัจจุบันสามารถใช้ได้เฉพาะ Lazarus เวอร์ชั่น Trunk (สำหรับ Developer) เท่านั้น ยังไม่สามารถใช้ได้กับเวอร์ชั่นทั่วไป =====2. Generic Class===== คือการสร้าง Class ที่ใช้กับ DataType ใดๆก็ได้ ไม่เฉพาะเจาะจง คล้ายกับ Generic Procedure/Function แค่เปลี่ยนเป็น Class เท่านั้น อย่างไรก็ตาม สำหรับ Generic Class นั้น ก่อนการนำไปใช้ จะต้องมีการสร้าง Class เป้าหมาย ขึ้นมาก่อนเสมอ รูปแบบของการประกาศและการสร้าง Class สรุปได้ดังนี้ ^ Topic ^ Format ^ |การประกาศ Generic Class| type generic TList = class Items: array of T; procedure Add(Value: T); end; | |การสร้าง Class จาก Generic Class| Type TIntegerList = specialize TList; TPointerList = specialize TList; TStringList = specialize TList; |