Class template with multiple parameters

Prerequisite: Templates in C++

While creating templates, it is possible to specify more than one type. We can use more than one generic data type in a class template. They are declared as a comma-separated list within the template as below:
Syntax:

template<class T1, class T2, ...>
class classname
{
      ...
      ...
};
filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate
// Class template with multiple parameters
  
#include<iostream>
using namespace std;
  
// Class template with two parameters
template<class T1, class T2>
class Test
{
        T1 a;
        T2 b;
    public:
        Test(T1 x, T2 y)
        {
            a = x;
            b = y;
        }
        void show()
        {
            cout << a << " and " << b << endl;
        }
};
  
// Main Function
int main()
{
    // instantiation with float and int type
    Test <float, int> test1 (1.23, 123);
      
    // instantiation with float and char type
    Test <int, char> test2 (100, 'W');   
      
    test1.show();
    test2.show();
      
    return 0;
}

chevron_right


Output:

1.23 and 123
100 and  W

Explanation of the code:

  • In the above program, the Test constructor has two arguments of generic type.
  • The type of arguments is mentioned inside angle brackets < > while creating objects.
  • When argument is more than one, they are separated by commas.
  • Following statement
    Test  test1 (1.23, 123);

    tells the compiler that the first argument is of type float and another one is int type.

  • During creation of objects, constructor is called and values are received by template arguments.

This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.