954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

templates and maps

I've got the following code:

template <typename T> int Histogram<T>::get_occurances(const T& obj)
{
         map<T,int>::iterator find_occur = frequency.find(obj);
         
         if ( find_occur == this->frequency.end() )
         {
            return 0;
         }
         
         return ( find_occur->second );
}


The following line always gives me an error saying ';' expected before find_occur.

map::iterator find_occur = frequency.find(obj);

If I change the first argument of the map to something other than T, then it works fine, but I need the template type. Is there something I'm doing wrong?

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

A type that depends on a template parameter needs to be qualified with the typename keyword.

template <typename T> int Histogram<T>::get_occurances(const T& obj)
{
         typename map<T,int>::iterator find_occur = frequency.find(obj);
         
         if ( find_occur == this->frequency.end() )
         {
            return 0;
         }
         
         return ( find_occur->second );
}
eCharisma
Newbie Poster
8 posts since Apr 2006
Reputation Points: 10
Solved Threads: 1
 

Ahhh, thank you. I was actually looking into using a typename, but in a different context. I've never really understood why you have to qualify it with that.


Thanks man.

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You