依赖范围错误与stl

sha*_*har 3 c++ stl map

#include <iostream>
#include <map>
#include <string>

using namespace std;

template <class T>
class Counter
{
    public:
        Counter()
        {
            totalCount     
        }

        ~Counter()
        {
        }

        bool containsKey(T key)
        {
            map<T, double>::iterator it = counter.find(T);
            if (it == counter.end()) return false;
            return true;
        }

    private:
        map<T, double> counter;
        double totalCount;
};

int main()
{
    Counter<string> table;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这段代码甚至没有编译,我无法弄清楚错误是什么.任何帮助,将不胜感激.谢谢!

要编译的cmd

g++ counter.cpp
Run Code Online (Sandbox Code Playgroud)

错误是

error: need ‘typename’ before ‘std::map<T, double>::iterator’ because ‘std::map<T, double>’ is a dependent scope
Run Code Online (Sandbox Code Playgroud)

sas*_*hka 6

编译器知道T是模板声明中类型(typename)的名称,但它不知道std :: map :: iterator是一个类型还是不同的类型.因此编译器说你必须在此语句之前添加'typename'来告诉编译器它是一个类型的名称.

作为总结:改变

map<T, double>::iterator it = counter.find(T);
Run Code Online (Sandbox Code Playgroud)

typename map<T, double>::iterator it = counter.find(T);
Run Code Online (Sandbox Code Playgroud)