Consider a simple function template:
template <typename T>
void FunctionTemplate(T t){
}
void MyFunction(){
int a;
FunctionTemplate(a);
FunctionTemplate<int>(a);
}
In the first call to (FunctionTemplate(a)
), the compiler works out the type which raises the question, is there any reason for the existence of the second way of calling FunctionTemplate (FunctionTemplate<int>(a)
) or any compelling reasons where we could not use the first method?
Edit: My terminology my be a little off, so please edit as required.
Occasionally you will want to specify the template argument, even if you don't have to. Let's say your function takes an argument of type T
and you have an int
but you want the function to take it as a float
. Then you would need to explicitly say FunctionTemplate<float>(my_int)
.
There are also plenty of cases where the template parameter cannot be deduced. Consider the following:
template <typename T>
T FunctionTemplate() {
return T();
}
No matter how you call this, if you don't provide the template argument, the type of T
cannot be automatically deduced. The simple reason in this case is that the calling site says nothing about what it expects the return type to be.
For the terminology: when you do not specify the template arguments, the template is implicitly instantiated; when you do specify the template arguments, the template is explicitly instantiated.
Suppose you want to pass the function to another method as a parameter;
myAlgorithm( myFunction<int> );
Or suppose you want to guarantee a floating-point version of a function is used for speed;
myFunction<float>( 2.0 );
(forgetting to write 2.0f
isn't a problem now)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With