Hi guys I am only learning about templates now,I decided it really is a must,I know many programmers don't choose to learn it,but since the core library in c++ is built on templates and also many other libraries I think it's something I must learn,
anyway
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
template<class T>
T tFunc(T a,T b){
return a + b;
}
int main()
{
int result = tFunc(2.2,3.0);
double result2 = tFunc<double>(2,4.2); // will compile
double result2 = tFunc<double,double>(2,4.2); // won't compile
cout << result2 << endl;
}
as you can see on the lines with comments,how come when I include one double in the <> brackets the code compiles,but when I try to use to double it gives me an error?
You are creating a template with only one data type (class T).
To create a template that takes two types:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
template<class T, class U>
T tFunc(T a, U b)
{
return a + b;
}
int main()
{
int result = tFunc(2.2, 3.0);
double result2 = tFunc<double>(2, 4.2);
double result3 = tFunc<double, double>(2, 4.2);
std::cout << result << '\n' << result2 << '\n' << result3 << '\n';
}