Templates

Introduction

C++ में programming करते समय कई बार हमें ऐसे functions या classes लिखने पड़ते हैं जो अलग-अलग data types (int, float, double आदि) के लिए समान कार्य करते हैं। यदि हम हर data type के लिए अलग-अलग code लिखें, तो code लंबा और repetitive हो जाता है।

इस समस्या को हल करने के लिए C++ में Templates का उपयोग किया जाता है। Templates generic programming की सुविधा देते हैं, जिससे एक ही code को विभिन्न data types के लिए उपयोग किया जा सकता है।


Definition

Template C++ का एक ऐसा feature है जो हमें generic (सामान्य) functions और classes बनाने की सुविधा देता है, जो अलग-अलग data types के साथ काम कर सकते हैं।


Template का मुख्य उद्देश्य

  • Code reuse बढ़ाना
  • Repetition को कम करना
  • Flexible और generic programming करना
  • Maintainability को बेहतर बनाना

Types of Templates

1. Function Template

2. Class Template


Function Template

Syntax

template <class T>
returnType functionName(T parameter) {
// body
}

Example (Function Template)

#include <iostream>
using namespace std;

template <class T>
T add(T a, T b) {
return a + b;
}

int main() {
cout << add(10, 20) << endl;
cout << add(2.5, 3.5);

return 0;
}

Output:

30
6

Working को समझना

  • T एक generic data type है
  • compiler data type के अनुसार function create करता है
  • एक ही function multiple types के लिए काम करता है

Class Template

Syntax

template <class T>
class ClassName {
T data;
};

Example (Class Template)

#include <iostream>
using namespace std;

template <class T>
class Demo {
public:
T x;

void setValue(T val) {
x = val;
}

void show() {
cout << "Value: " << x;
}
};

int main() {
Demo<int> d1;
d1.setValue(10);
d1.show();

cout << endl;

Demo<float> d2;
d2.setValue(5.5);
d2.show();

return 0;
}

Output:

Value: 10
Value: 5.5

Important Points

  • template <class T> या template <typename T> दोनों सही हैं
  • Compiler run time पर नहीं, compile time पर type decide करता है
  • Templates code duplication को कम करते हैं
  • STL (Standard Template Library) templates पर आधारित है

Advantages

  • Code reuse बढ़ता है
  • Flexible programming संभव होती है
  • Maintenance आसान होता है
  • Generic solutions बनाए जा सकते हैं

निष्कर्ष

Templates C++ का एक महत्वपूर्ण feature है जो generic programming को संभव बनाता है। यह code को reusable, efficient और flexible बनाता है और modern programming में इसका व्यापक उपयोग होता है।

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top