Reputation: 21
In the page on std::inplace_merge at cppreference.com, it gives an example of using inplace_merge for merge sort. My question has to do with the way they've implemented merge sort with template arguments for the type of iterator.
When it calls merge_sort in the main function, no argument is passed in to tell what kind of iterator we're using. Yet I've compiled this code and it runs fine. How come you don't have to tell merge_sort what kind of iterator we're using? How would you even do that?
#include <vector>
#include <iostream>
#include <algorithm>
template<class Iter>
void merge_sort(Iter first, Iter last)
{
if (last - first > 1) {
Iter middle = first + (last - first) / 2;
merge_sort(first, middle);
merge_sort(middle, last);
std::inplace_merge(first, middle, last);
}
}
int main()
{
std::vector<int> v{8, 2, -2, 0, 11, 11, 1, 7, 3};
merge_sort(v.begin(), v.end()); // <----------------- ?
for(auto n : v) {
std::cout << n << ' ';
}
std::cout << '\n';
}
Upvotes: 0
Views: 51
Reputation: 7374
This happens because of Template argument: deduction
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.
Upvotes: 1