hash_map with string keys :"instantiated from here" error & STL questions

David Fang fang@csl.cornell.edu
Tue Aug 28 21:23:00 GMT 2007


> Greetings; that my first gcc post. Here's the code, that causes the error.

> Compiling it, i get:

[snip snip snip snip snip]

> /usr/include/c++/4.1.3/ext/hashtable.h:596: error: no match for call to 
> ?(const __gnu_cxx::hash<std::basic_string<char, std::char_traits<char>, 
> std::allocator<char> > >) (const std::basic_string<char, 
> std::char_traits<char>, std::allocator<char> >&)?
> make: *** [build/Debug/GNU-Generic/FinancialProductsMatrix.o] Error 1
>
> Build failed. Exit value 2.

Hi,

> 1/I got an answer, that the error has to do with hash_map not being able to 
> handle string objects. First, can somebody confirm that?
> 2/I read somewhere, that hash_map is not "standard". What does this mean? 
> Doesn't libstdc++ implement the sgi STL "standard"?

 	Indeed, you need to help the compiler by telling it how to hash 
std::string, using a "template specialization".

@example
namespace HASH_MAP_NAMESPACE {
/**
         Explicit template specialization of hash of a string class,
         which just uses the internal char* representation as a wrapper.
  */
template <>
struct hash<std::string> {
         size_t operator() (const std::string& x) const {
                 return hash<const char*>()(x.c_str());
 	// hash<const char*> already exists
         }
};
}
@end example

... where HASH_MAP_NAMESPACE is '__gnu_cxx' for GNU g++.  (Could be 
something else for other compilers.  I let autoconf figure that out...)

The above excerpt should appear early enough before the template is 
actually "instantiated" to take effect.

> 3/ If this is the answer, where can i find an libstdc++ API, that contains 
> the libstdc++ STL API as well? Maybe something the SUN JDK API -yes
> i am a Java coder wanting to learn C++...

Welcome to the light!
The above solution may require a little understanding of templates.
"Template specialization" is a way of telling the compiler to do something 
different given a particular input types, for example.  "Instantiation" is 
the time at which a template is called upon to be expanded with parameters 
substituted, and usually occurs 'on-demand'.  Specialization needs to be 
done in the same namespace as the primary (original) template.

So you can paste the above into a header and include it where strings need 
to be hashed.

> 4/Then i followed this sgi STL example: 
> http://www.sgi.com/tech/stl/hash_map.html, which didn't work.
> Since i am now learning C++, can somebody tell me what i must and explain a 
> little? or point me to a link about this issue?

Hope this serves as a start.

Fang



David Fang
Computer Systems Laboratory
Electrical & Computer Engineering
Cornell University
http://www.csl.cornell.edu/~fang/
 	-- (2400 baud? Netscape 3.0?? lynx??? No problem!)



More information about the Libstdc++ mailing list