Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are template types optional to use?

Tags:

c++

Assume the following code:

template<typename T>
   void print(T in){
   std::cout << in << std::endl;
}

Both of the following can be used:

print(5);
print<int>(5);

So are the types optional or is there a reason for having them?

like image 717
Joe Avatar asked Jan 27 '23 11:01

Joe


1 Answers

There is a mechanism called template argument deduction. From cppreference:

In order to instantiate a function template, every template argument must be known, but not every template argument has to be specified. When possible, the compiler will deduce the missing template arguments from the function arguments. This occurs when a function call is attempted, when an address of a function template is taken, and in some other contexts: [...]

In your example the compiler can deduce the template argument T because 5 is an int. Hence void print<int>(int in) is called.

So are the types optional or is there a reason for having them?

Sometimes you still need to write the template arguments explicitly. For example if you want some conversion to happen you could call

print<double>(5);
print<int>(5.3);  // prints 5

Does the same hold true for template classes?

Up to C++17 it was common to have function templates to create instances of class templates. Look at std::make_pair as an example. Without it there was no way to ommit the template arguments

auto x = std::pair(1,2);          // before c++17: error missing template arguments
auto x = std::pair<int,int>(1,2); // OK
auto x = std::make_pair(1,2);     // OK deduces std::make_pair<int,int>  

Since C++17 there is class template argument deduction which allows you to write:

std::pair p(2, 4.5);     // deduces to std::pair<int, double> p(2, 4.5);
like image 139
463035818_is_not_a_number Avatar answered Jan 29 '23 00:01

463035818_is_not_a_number