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;
}
"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;
}