Problems with templates

Hello

I don't understand templates. If i want to create for instance very simple function which adds two variables of generic type T together and returns the sum as T as long as it supports + and - etc....operators. I tried something like below:
By the way:Is its declaration in header file
template <typename T>;
sum( T &v1,T &v2, T &v3);

Or something else? Thank you very much in advance :)


1
2
3
4
5
  template <typename T>
sum( T &v1,T &v2, T &v3) {
	v3 = v2 + v1;
	return v3;	
}
1
2
3
4
5
 template <typename T>
sum( T &v1,T &v2, T &v3) {
	v3 = v2 + v1;
	return v3;	
}


Should be :
1
2
3
4
5
 template <typename T>
T sum( T &v1,T &v2, T &v3) {
	v3 = v2 + v1;
	return v3;	
}
"Sum" is somewhat different from "Add". Basically, if you want to sum three numbers, you have to add up all the three numbers. You don't need to use references because they are redundant.

Here are the two versions :
1.
1
2
3
4
template <typename T>
T add( T v1, T v2) {
	return v1 + v2;	
}


2.
1
2
3
4
template <typename T>
T sum( T v1, T v2, T v3) {
	return v1 + v2 + v3;	
}
Last edited on
Thank you very much for answering!
I would like to still ask why this won't work. I think this should be correct ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <typename T>
T sum(T &v1, T &v2, T &v3) {
	v3 = v2 + v1;
	return v3;
}

int main(void) {
int a = 7, b = 2;
double c = 3.364673, d = 6.345636;
std::string s1 = "Hello ", s2 = "world!";
std::cout << "Summing together " << a << " and " << b << ". Got " << sum<int>(a,b) << ". Should be: 9." << std::endl;
	std::cout << "Summing together " << c << " and " << d << ". Got " << sum<double>(c,d) << ". Should be: 9.71031." << std::endl;
	std::cout << "Summing together " << s1 << " and " << s2 << ". Got " << sum<std::string>(s1,s2) << ". Should be: Hello world!" << std::endl;
}

See above. If you intend to add two numbers only, use the "Add" version not the "Sum" version.
Thank you!
Now everything works very well.
Topic archived. No new replies allowed.