×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

C++ Templates | Find output programs | Set 2

This section contains the C++ find output programs with their explanations on C++ Templates (set 2).
Submitted by Nidhi, on September 03, 2020

Program 1:

#include <iostream>
using namespace std;

template <class Type>
Type fun(Type num)
{
    int f = 1;

    while (num > 0) {
        f = f * num;
        num--;
    }
}

int main()
{
    int fact = 0;

    fact = fun<int>(5);

    cout << fact;

    return 0;
}

Output:

120

Explanation:

The above code will print 120 on the console screen. In the above program, we defined a generic function using templates with argument num. Here we used the "class" keyword instead of "typename". This function is used to calculate the factorial of the specified number.

Now coming to the main() function. Here we passed integer value in the function fun(). Then it will return 120 that will be printed on the console screen.

Program 2:

#include <iostream>
using namespace std;

template <class T1, class T2>
class Sample {
    T1 var1;
    T2 var2;

public:
    Sample(T1 v1, T2 v2)
    {
        var1 = v1;
        var2 = v2;
    }
    void print()
    {
        cout << var1 << endl;
        cout << var2 << endl;
    }
};

int main()
{
    Sample<char, float> S1('A', 3.14F);
    Sample<int, double> S2(101, 3.14);

    S1.print();
    S2.print();

    return 0;
}

Output:

A
3.14
101
3.14

Explanation:

In the above program, we created a generic class Sample with two types T1 and T2. The Sample class contains two data members' var1, var2, and a parameterized constructor that will initialize the data member's var1 and var2.

Here we also created a print() member function to print the values of var1 and var2. Now coming to the main() function. Here we created two objects S1 and S2 with different types of values. Then we called print() function using S1 and S2 that will print the values of data members.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.