What will my function return? Is it automatically determined? Does it return an integer if x is an integer and y is a float, does it return a string if x is a char and y is a char? Is it an int if y is a char and x is a char?
How can I exercise good practices in ensuring my function returns what I want it to?
1) Your syntax is wrong. On line 1, that should be a >, not a ). And on line 2, you don't need the <undefType>.
2) A function template definition should specify the return type, just like a normal function definition. The return type can be one of the template parameters, if necessary:
3) In the example code you've posted, x and y cannot be different types. If you want it to be possible to make them different types, you need to use multiple template parameters:
1 2
template <class undefType1, class undefType2>
undefType1 function(undefType1 x,undefType2 y) {undefType1 b = x+y; return b; }
Oh, I know the syntax and all that, I was kind of in a rush, but what I want to know is how you specify the return type?
Is that specified when you call the function, like function<int>(arguments)? Is the return type always going to be int in that function no matter the parameters? I had heard somewhere that the first parameter determined the return type.
I've already answered this. The same way as you do in any other function definition. You put it before the name of the function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Normal function
defined_type myFunction(defined_type a, defined_type b)
{
defined_type c;
return c;
}
// Function template
template <class undefType>
undefType myFunction(undefType a, undefType b)
{
undefType c;
return c;
}
C++ is statically typed. This means types are determined at compile-time.
The key here is that a function template is not a function. A function template generates functions. A template is just like an empty glass. It's empty at first, but you can fill it in with water, tea, coffee, or juice. Oh and also you duplicate the glass each time.
The return type of your function template is a return type named "undefType1". This is a placeholder filled in (at compile time) once you actually call the function template with corresponding valid types.