function objects in C + + templates

Source: Internet
Author: User

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&LT;STD::string,int, str_hash>A;4Std::cout <<"hashcode:"<< A.hashcode ("ABC") <<Std::endl;5 6A&LT;STD::string,int, STD::HASH&LT;STD::string>>h;7Std::cout << H.hashcode ("ABC") <<Std::endl;8 9A&LT;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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.