If I understand correctly, in the Standard Library, there exists this definition of std::sort()
:
template< class RandomIt >
constexpr void sort( RandomIt first, RandomIt last );
Suppose I have such a vector that I wish to sort:
std::vector<int> data {9, 7, 5, 3, 1};
If this is the case, then why can I just write:
std::sort(data.begin(), data.end());
as opposed to requiring:
std::sort<std::vector<int>::iterator>(data.begin(), data.end());
If possible, could someone provide a generic explanation? I think I've definitely seen more than one instance of this where the template type almost seems to be automatically deduced... or is it being automatically deduced...?
CodePudding user response:
or is it being automatically deduced...?
Yes.
When a template parameter is used for a function parameter, the template argument can be deduced from the argument passed to the function. So, in this case RandomIt
is deduced from the arguments data.begin()
and data.end()
.