带有模板化容器的模板函数作为参数 - 奇怪的拼写错误

时间:2013-11-07 16:03:14

标签: c++ templates c++11

我得到了一些没有任何意义的奇怪错字错误。我担心这可能是一个C ++编译器问题(在Mac上有10.6.8和Xcode 3.x)。如果有人能够真正发现问题,我将不胜感激:

template<typename T> int getIdxInVector(const std::vector<T>&  vec, const T& toMatch)
{
std::vector<T>::const_iterator cit = std::find(vec.begin(),vec.end(),toMatch);
return( cit != vec.end() ? cit - vec.begin() : -1 );
}

以下是我遇到的错误:

LooseFunctions.h:27: error: expected `;' before 'cit'
LooseFunctions.h:28: error: 'cit' was not declared in this scope
LooseFunctions.h:27: error: dependent-name 'std::vector<T,std::allocator<_CharT> >::const_iterator' is parsed as a non-type, but instantiation yields a type
LooseFunctions.h:27: note: say 'typename std::vector<T,std::allocator<_CharT> >::const_iterator' if a type is meant

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

const_iterator是一个从属名称,因此您需要使用typename来指定它引用的类型:

typename std::vector<T>::const_iterator = ...

请注意,C ++ 11使这更容易:

auto cit = std::find(vec.begin(),vec.end(),toMatch);