c++ - 迭代器的模板参数 : function infers type when called?

标签 c++ templates iterator

在 std::inplace_merge 上的页面中 cppreference.com ,它给出了使用 inplace_merge 进行合并排序的示例。我的问题与他们使用迭代器类型的模板参数实现合并排序的方式有关。

当它在主函数中调用 merge_sort 时,没有传入任何参数来告诉我们正在使用哪种迭代器。但是我已经编译了这段代码并且运行良好。为什么您不必告诉 merge_sort 我们正在使用哪种迭代器?你会怎么做?

#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';
}

最佳答案

发生这种情况是因为 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.

关于c++ - 迭代器的模板参数 : function infers type when called?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58263556/

相关文章:

python - 列表迭代器中的项目值未更新

c++ - windows接收到中断的处理时间

c++ - 对 C++ 11 可变模板参数进行操作,存储到元组中

java - 使 ArrayList<LinkedList<String>> 成为可迭代对象

c++ - 无法从函数参数的默认参数中推断出模板参数

templates - 无法从 FieldType* 推断出 T* 的模板参数(仅限 Visual C++)

python - 如何迭代坐标列表并计算它们之间的距离?

C++ 返回错误的代码行

c++ - 关于在 C++/SDL/OpenGL 中实现视差滚动的问题

c++ - openCV 中的彩色对象跟踪不断检测皮肤