There is no implicit conversion from std::string
to const char*
which would be required to make your example work.
You may call string::c_str()
to explicitly do this "conversion"...
hash<const char*> PassHash;
string password;
password = "Hello World";
cout << PassHash(password.c_str());
... but this will only calculate the hash of the string pointer because there is no specialization for hash<const char*>
! So this only matches the generic pointer specialization hash<T*>
.
What you propably really want is hash over the entire character array of the string, so if one character of the string changes, you (most likely) get a different hash value.
For this you could use the hash<std::string>
specialization. This works for both const char*
and std::string
arguments as expected, because std::string has a conversion constructor that takes a const char*
.
Example:
const char* password1 = "Hello World";
string password2 = "Hello World";
hash<const char*> charPtrHasher;
// This only calculates a hash from the value of the pointer, not from
// the actual string data! This is why you get a different hash for each.
cout << "Test 1:\n";
cout << charPtrHasher(password1) << endl << charPtrHasher(password2.c_str()) << endl;
hash<std::string> stringHasher;
// This correctly calculates the hash over all characters of the string!
cout << "\nTest 2:\n";
cout << stringHasher(password1) << endl << stringHasher(password2) << endl;
Live Demo: http://coliru.stacked-crooked.com/a/047c099f5dcff948