We have many reasons to use templates, but it is important to remember that templates should be defined in header files. Because the code for specific types is generated when we instantiate them
// for Int, double, float
template <class T>
class AddElements {
T val;
public:
AddElements(T obj) {
this->val = obj;
}
T add(T obj) {
return (val + obj);
}
};
Sometimes, we might need to define a template specialization for a specific type
//template for string and additional function concatenate
template <>
class AddElements<string> {
string val;
public:
AddElements(string str) {
this->val = str;
}
string concatenate(string str) {
this->val.append(str);
return this->val;
}
};
more than one template argument, default value for template argument
template<typename T, typename U = double>
class mPair {
public:
T first;
U second;
mPair(T f, U s) : first(f), second(s) {}
bool operator > (const mPair& obj) {
return this->second > obj.second;
}
};
use case :
int main()
{
AddElements<int> ae(4);
int sum = ae.add(16); // 20
AddElements<string> s_ae("hello ");
string str = s_ae.concatenate("world...!"); // hello world...!
mPair <string> df_mp("default", 8.4);// second argument type name is as default -> double
cout << " default first " << df_mp.first << " second: " << df_mp.second << endl;
mPair<string, int> mp("str1", 40); //
cout << " first " << mp.first << " second " << mp.second << endl;
mPair<string, int> mp1("str2", 8);
mPair<string,int> mpmx = getMax<mPair<string,int>>(mp, mp1);
mPair<string, int> mpmx1 = getMax(mp, mp1);// the compiler can deduce the template parameters from the type of mp
return 0;
}
Top comments (0)