What do this mean? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What do this mean?

template<class T> What do class represent I mean why do we use class here and can we use anything else?

7th Jan 2018, 11:33 AM
Panda
Panda - avatar
2 Answers
7th Jan 2018, 12:53 PM
Md. Nafis Ul Haque Shifat
Md. Nafis Ul Haque Shifat - avatar
+ 5
Other use of template is for typename, it is used to ease writing a method where multiple types of data are acceptable. For example, you can use typename template to ease your work writing a function that does arithmetic operation (e.g. multiply), while you want the function to support multiple types of data to work with. So, instead of writing one function for each of the data types (short, int, float, double) you go write a template of typename, then use the template in your function, by that, your function now works fine with multiple types involved. // Code example: #include <iostream> using namespace std; template <typename T> T multiply(T num1, T num2) { return num1 * num2; } int main() { short s1{21}, s2{2}; int i1{2}, i2{21}; float f1{7}, f2{6}; double d1{6}, d2{7}; cout << "multiply of short result: " << multiply(s1, s2) << endl; cout << "multiply of int result: " << multiply(i1, i2) << endl; cout << "multiply of float result: " << multiply(f1, f2) << endl; cout << "multiply of double result: " << multiply(d1, d2) << endl; return 0; } Hth, cmiiw
7th Jan 2018, 1:31 PM
Ipang