Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason for explicitly stating the template type?

Tags:

c++

templates

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.

like image 206
R4D4 Avatar asked Mar 09 '13 19:03

R4D4


2 Answers

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.

like image 129
Joseph Mansfield Avatar answered Oct 06 '22 00:10

Joseph Mansfield


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)

like image 37
Dave Avatar answered Oct 05 '22 23:10

Dave