在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/