Coupon Accepted Successfully!


Class Templates With More Parameters

Similar to functions, classes can be declared to handle different data types. Such classes are known as class templates. These classes are of generic type, and member functions of these classes can operate on different data types. The class template may contain one or more parameters of generic data type. The arguments are separated by commas with a template declaration. The declaration is as follows:

Templates with multiple parameters

template <class T1, class T2>

class name_of_ class


// class declarations and definitions


17.6 Write a program to define a constructor with multiple template variables.
template <class T1, class T2>
class data
data (T1 a, T2 b)
{cout<<“\n a=”<<a <<“ b=”<<b;}
int main()
data <int,float> h(2,2.5);
data <int,char> i(15,‘C’);
data <float,int> j(3.12,50);
return 0;}
a = 2 b = 2.5
a = 15 b = C
a = 3.12 b = 50
Explanation: In the above program, the data constructor has two arguments of generic type. While creating objects, the type of arguments is mentioned in angle brackets. When arguments are more than one, they are separated by commas. Consider the statement data <int, float> h(2,2.5); it tells the compiler that the first argument is of integer type and the second argument is of float type. When objects are created, constructors are called, and values are received by the template arguments. The output of the program is as given above.

Test Your Skills Now!
Take a Quiz now
Reviewer Name