C++ std::find() 和模板参数

标签 c++ templates find

C++ reference ,查找方法定义为

template <class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val);

但是,当我使用 find 方法时,我使用 find() 方法而没有明确描述 InputIterator 和 T。

比如我用

std::vector<T> aList
...
std::list<int>::iterator pointer = std::find(aList.begin(), aList.end(), *it);

不是这个

std::list<int>::iterator pointer = std::find<std::list<int>::iterator, int>(aList.begin(), aList.end(), *it);

它是如何工作的?为什么我使用find方法时不需要指定类型?

最佳答案

这叫做参数类型推导。来自 C++ 标准(C++11 版本):

(§14.8.2/1) When a function template specialization is referenced, all of the template arguments shall have values. The values can be explicitly specified or, in some cases, be deduced from the use or obtained from default template-arguments. [ Example:

void f(Array<dcomplex>& cv, Array<int>& ci) {
  sort(cv);   // calls sort(Array<dcomplex>&)
  sort(ci);   // calls sort(Array<int>&)
}

and

void g(double d) {
  int i = convert<int>(d);   // calls convert<int,double>(double)
  int c = convert<char>(d);  // calls convert<char,double>(double)
}

— end example ]

类型推导仅在存在参数时进行,即它仅适用于函数模板,不适用于类模板(甚至不适用于构造函数)。

类型推导会导致非常复杂的歧义,尤其是在给出多个模板特化和/或重载函数定义时。在某些情况下,这是不可能的,然后您必须使用尖括号语法显式指定部分或全部模板参数。

关于C++ std::find() 和模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16889098/

相关文章:

c++ - 模板函数中的默认参数值,取决于类型

c++ - 有没有一种方法可以将别名模板推导为模板模板参数,同时仍保留其被推导上下文的属性

vb.net - FileSystem.GetFiles()+ UnauthorizedAccessException错误?

c++ - 使用 find 检查,如果我在字符串中有下划线

c++ - gnuplot-cpp 无法将命令提供给管道

c++ - 基类变量为 `not declared in its scope`

c++ - TF_NewTensor 分割错误 : Possible Bug?

c++ - 如何确定tcp客户端是否在C++中连接

c++ - void_t 和带有 decltype : are they completely interchangeable? 的尾随返回类型

python - JavaScript 的 Array.prototype.find 的 python 等价物是什么?