Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dependent scope error with stl

#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;
}

this code doesn't even compile and I can't figure out what's the error. Any help would be appreciated. Thanks!

cmd to compile

g++ counter.cpp

The error is

error: need ‘typename’ before ‘std::map<T, double>::iterator’ because ‘std::map<T, double>’ is a dependent scope
like image 550
shashydhar Avatar asked May 04 '26 14:05

shashydhar


1 Answers

Compiler knows that T is the name of a type (typename) from your template declaration but it doesn't know if std::map::iterator is a type or something different. So as compiler says you have to add 'typename' before this statement to tell compiler it's a name of a type.

As a summary: change

map<T, double>::iterator it = counter.find(T);

to

typename map<T, double>::iterator it = counter.find(T);
like image 167
sasha.sochka Avatar answered May 06 '26 04:05

sasha.sochka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!