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?
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);
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