为什么C++标准为模板定义了两个阶段查找?非依赖声明和定义的查找是否也可以推迟到实例化阶段?
这段代码不能用clang ++ 6.0或g ++ 4.9.1编译(代码没有意义,但这是实现它的最小例子):
#include <forward_list>
template<typename T>
T getItem(typename std::forward_list<T>::const_iterator it) {
return *it;
}
template<typename T>
void foo() {
std::forward_list<T> list;
auto item = getItem(list.cbegin());
}
template<typename T>
void bar(const std::forward_list<T>& list) {
auto item = getItem(list.cbegin());
}
int main() {
std::forward_list<int> list;
bar(list);
}
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
t2.cpp:17:17: error: no matching function for call to 'getItem'
auto item = getItem(list.cbegin());
^~~~~~~
t2.cpp:22:5: note: in instantiation of function template specialization 'bar<int>' requested here
bar(list);
^
t2.cpp:4:3: note: candidate template …Run Code Online (Sandbox Code Playgroud)