This question already has answers here:
Where and why do I have to put the “template” and “typename” keywords?
                                
                                    (6个答案)
                                
                        
                                5年前关闭。
            
                    
我收到奇怪的错别字错误,没有任何意义。我担心这可能是C ++编译器问题(在具有10.6.8和Xcode 3.x的Mac上)。如果有人能真正发现问题,我将不胜感激:

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


谢谢你的帮助!

最佳答案

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

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


请注意,C ++ 11使此操作更容易:

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

09-20 21:37