In C + + template class map, a parameter is a compare type, which is a comparison function, which is fully defined as follows:
template< class Key, class T, class Compare = Std::less <Key>, class Allocator = std::allocator<std::p air<constclass map;
The function is passed as a class that uses the overloaded operator () to transform a function pointer to a class. In practice, you can also write your own class in this style.
1 template <typename Key, TypeName Value, class Hash > class A { 3 has h Hash_fn; public : A (): Hash_fn (hash ()) { 6 7 8 9 size_t hashcode (key key) {return HASH_FN (key);} 10 11 };
The third argument hash is a function object, which is implemented by the overloaded operator (), whose key of a string type is defined as follows:
1 struct Str_hash {2 operator () (const std::stringconst3 {4 return 0; 5 }6 };
When the HASH_FN (key) function is called, the overloaded function is called, and the conversion is implemented. Because the C + + standard library contains a large number of classes of this type of style, we can invoke the standard class by default parameters so that the template class A above can be defined as follows:
class Hash = std::hash<key>>
The test procedure is as follows:
1 intMainintargcChar*argv[]) {2 3A<STD::string,int, str_hash>A;4Std::cout <<"hashcode:"<< A.hashcode ("ABC") <<Std::endl;5 6A<STD::string,int, STD::HASH<STD::string>>h;7Std::cout << H.hashcode ("ABC") <<Std::endl;8 9A<STD::string,int>H2;TenStd::cout << H.hashcode ("ABC") <<Std::endl; One A return 0; -}
The test results are as follows:
1 Functiontem 2 hashcode:03335097746143350977461
function objects in C + + templates