0

Why templates are used in c++?

6th Dec 2016, 8:09 AM
Dharm Vashisth
Dharm Vashisth - avatar
3 Answers
+ 1
Sometimes you need to create same class for different types. For example you have a class that takes integer parameters only. But you need the class for float types as well. Instead of creating the same class twice and write code for both of them, you design your code accordingly by creating a template.
6th Dec 2016, 10:37 AM
meceware
+ 1
template <class A, class B> public static A sum(A x, B y) { A a = A(y); return a + y; } this will work for any two data types but will give the results expected only for numerical data types. you could now override it to make it much more efficient.
6th Dec 2016, 1:02 PM
NICKALL [EP]
NICKALL [EP] - avatar
0
example please
6th Dec 2016, 12:37 PM
Dharm Vashisth
Dharm Vashisth - avatar