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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.