Introduction for C++ Templates
C++ का Templates ये feature बहुत ही उपयुक्त है | ये generic programming के लिए इस्तेमाल किया जाता है |
C++ Templates को दो प्रकार से इस्तेमाल किया जाता है |
- Function Templates
- Class Templates
1. Function Templates
C++ Templates में 'template' keyword के साथ 'typename' या 'class' keyword का इस्तेमाल किया जाता है |
Syntax for Function Templates
ये Function Template का syntax है | इसमें जो type है वो placeholder है, जो parameter की values दी जाती है, उसके हिसाब से Compile-time पर basic data type लेता है | For Example,अगर parameter में 4 और 5 ये values ली तो वो दोनों के data type integer लेगा |
template <class type> //can replace 'class' keyword by 'typename' keyword return_type function_name(parameters_list){ // Function body; }
Program में template keyword के साथ 'class' ये keyword लिया है , चाहे तो 'typename' keyword का भी इस्तेमाल किया जा सकता है |
class 'X' को define किया गया है | इसका मतलब जो भी User parameter(s) की values लिखेगा वहा पर उसका data type; compile-time पर compiler दे देता है |
Source Code :Output :#include <iostream.h> using namespace std; template <class X> //can replace 'class' keyword by 'typename' keyword X func(X a, X b){ return a; } int main() { cout<<func(9, 5)<<endl; // func(int, int); cout<<func('a', 'b')<<endl; //func(char, char); cout<<func(3.7, 5.6)<<endl; //func(double, double); return 0; }
9 a 3.7
2. Class Templates
Class Templates; Function Templates के जैसे ही होता है |
Class Templates को generic Templates भी कहा जाता है |
class का इस्तेमाल जैसे सामान्य तरीके से c++ program में किया जाता है वैसे ही Class Template में किया जाता है |
Syntax for Class Template
template//can replace 'class' keyword by 'typename' keyword class class_name{ // Class body; }
Example for Class Template
Source Code :Output :#include <iostream.h> using namespace std; template <class C> class A{ private: C a, b; public: A(C x, C y){ a = x; b = y; } void show(){ cout<<"Addition of "<<a<<" and "<<b<<" is "<<add()<<endl; } C add(){ C c = a + b; return c; } }; int main(){ Aaddint(4, 5); A addfloat(4.6, 8.9); A adddouble(3.145, 5.268); addint.show(); cout<<endl; addfloat.show(); cout<<endl; adddouble.show(); return 0; }
Addition of 4 and 5 is 9 Addition of 4.6 and 8.9 is 13.5 Addition of 3.145 and 5.268 is 8.413