C++ Template Question

I have tried the following code , it doesnt work
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>

using namespace std;

template <typename T>
T add (T & a, T & b);

template <typename T>
T add (T & a, T & b)
{
	return a + b;
}

int main()
{
	int i = 10;
	double d = 20.5;
	
	cout << add<double>(i, d) << "\n";
	
	return 0;
}

But i changed the following code ..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>

using namespace std;

template <typename T>
T add (T a, T b);

template <typename T>
T add (T a, T b)
{
	return a + b;
}

int main()
{
	int i = 10;
	double d = 20.5;
	
	cout << add<double>(i, d) << "\n";
	
	return 0;
}

then output ..
30.5


I dont know why it failed by using reference value
closed account (o1vk4iN6)
You'd be creating a temporary value (implicit conversion from int to double) to be able to pass by reference. Perhaps RValue would be a better term here, they shouldn't be modified so they need to be passed as const.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <typename T>
T add (const T& a, const T& b)
{
	return a + b;
}


int main()
{
	int i = 10;
	double d = 20.5;
	
	cout << add<double>(i, d) << "\n";
	
	return 0;
}
Last edited on
Topic archived. No new replies allowed.