முக்கிய உள்ளடக்கத்திற்குச் செல்லவும்
eLearner.app
தொகுதி 8 · பாடம் 1 இன் 2பாடத்திட்டத்தில் 17/18~12 min
தொகுதி பாடங்கள் (1/2)

செயல்பாட்டு வார்ப்புருக்கள்

Templates allow writing generic code in C++. Through templates, we can define functions or classes that operate on generic type parameters, letting the compiler generate the actual code for the specific types requested.

Defining a Function Template

To define a function template, we precede the function definition with the template keyword, followed by the list of type parameters enclosed in angle brackets <>. Commonly, typename or class is used to declare a generic type.

Code
// T is the generic type parameter
template <typename T>
T add(T a, T b) {
    return a + b;
}

Function Call and Template Argument Deduction

When we call the function, we can explicitly specify the type in angle brackets:

Code
int res1 = add<int>(5, 10);
double res2 = add<double>(3.14, 2.71);

However, the C++ compiler is usually able to deduce the type automatically from the passed input parameters (Template Argument Deduction):

Code
int res1 = add(5, 10); // The compiler deduces that T is int

Try it yourself

உடற்பயிற்சி#cpp.m8.l1.e1
முயற்சிகள்: 0ஏற்றுகிறது…

Define a function template named myMax that takes two parameters of generic type T and returns the greater of the two.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Start by writing `template <typename T>` followed by the signature `T myMax(T a, T b)`.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

உடற்பயிற்சி#cpp.m8.l1.e2
முயற்சிகள்: 0ஏற்றுகிறது…

Write a function template named printPair that takes two parameters of different generic types T1 and T2 and prints the two arguments separated by a space using std::cout.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

The template declaration must specify two parameters: `template <typename T1, typename T2>`.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்