Template processing of strings in C + + _c language

Source: Internet
Author: User

The template role in C + + is to combine functions that are only of different types but functionally similar, but sometimes the functions in template do not satisfy all type invocations. As shown below:

Template <class kty>
inline int hash_wrap (const kty& k)
{return
(int) k;
}

all numeric types use the template without problems, but string types do not, because type conversions with string to int are not supported (during compilation). So we need to add a support for string outside the template, and the code is as follows:

Template <>
inline int hash_wrap<string> (conststring & k)
{return
k.size ();
}

Where template <> indicates that the function is an extension of the template type,<string> indicates that the string type of the original template is overwritten.

For example, the following two examples are as follows:

Example 1:

Template <class kty>
inline unsigned int get_size (const kty&k)
{return
sizeof (kty);
}
template <>
inline unsigned int get_size (conststring& k)
{return
k.length () + 1;
}

Example 2:

 template <class kty> inline bool Cmp_key (const kty& K, constchar* dest) {retur
n k = = * (kty*) dest;; Template <> inline bool Cmp_key (const string& k,const char* dest) {return strcmp (K.c_str (), dest) = 0;} 

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.