Templates

Jun 3, 2018 at 6:26pm
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>

using namespace 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?


thanks
Jun 3, 2018 at 7:09pm
closed account (E0p9LyTq)
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';
}

5
6.2
6.2
Last edited on Jun 3, 2018 at 7:18pm
Jun 3, 2018 at 7:40pm
thanks Furryguy,

Don't know how I didn't come to that conclusion haha

thanks :)
Jun 3, 2018 at 8:47pm
closed account (E0p9LyTq)
On a double-plus side I learned a couple of things about templates when I was bashing up my example. :D
Topic archived. No new replies allowed.