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

C++ C++;std::find()和模板参数,c++,templates,find,C++,Templates,Find,在中,find方法定义为 template <class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val); 模板 输入计算器查找(输入计算器第一,输入计算器最后,常量T&val); 但是,当我使用find方法时,我使用find()方法,而没有显式地描述InputIterator和T 例如,我使用 std::vector<

在中,find方法定义为

template <class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val);
模板
输入计算器查找(输入计算器第一,输入计算器最后,常量T&val);
但是,当我使用find方法时,我使用find()方法,而没有显式地描述InputIterator和T

例如,我使用

std::vector<T> aList
...
std::list<int>::iterator pointer = std::find(aList.begin(), aList.end(), *it);
std::向量列表
...
std::list::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);
std::list::iterator pointer=std::find(aList.begin(),aList.end(),*it);

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

,因为类型是推导出来的。编译器可以查看调用,并确定由于您正在传递一个值
aList.begin()
,迭代器的类型将是返回类型
aList.begin()
。与使用
*it
类似,编译器知道它是什么类型,因此可以推断作为函数参数传入的类型。

称为参数类型推断。从C++标准(C++ 11版本):

(§14.8.2/1)当引用函数模板专用化时,所有模板参数应具有值。这些值可以明确指定,或者在某些情况下,可以从使用中推断出来,或者从默认值中获得 模板参数。[示例:

void f(Array<dcomplex>& cv, Array<int>& ci) {
  sort(cv);   // calls sort(Array<dcomplex>&)
  sort(ci);   // calls sort(Array<int>&)
}
void f(数组和cv、数组和ci){
排序(cv);//调用排序(数组&)
排序(ci);//调用排序(数组&)
}

void g(double d) {
  int i = convert<int>(d);   // calls convert<int,double>(double)
  int c = convert<char>(d);  // calls convert<char,double>(double)
}
void g(双d){
int i=convert(d);//调用convert(double)
int c=convert(d);//调用convert(double)
}
-[结束示例]

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

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