Article 42: Understanding the dual meaning of TypeName

Source: Internet
Author: User

TypeName is identical to class in many cases, such as the following:

1 templame<typename t>2 ... 3 template<class t>4 ...

Article 42: Understanding the dual meaning of TypeName

1Template<typename c>2 voidprint2nd (ConstC Containter)3 {4     if(Containter.size () >=2){5 C::const_iterator iter (Containter.begin ());6++iter;7         intValue = *iter;8Cot <<value;9     }Ten}

The above formula cannot be compiled: The const_iterator is actually a nested subordinate name, and the compiler does not actually know that it is a type name. So unless we take the initiative to tell the compiler that this is a type name, it will get an error:

1 TypeName C::const_iterator iter (Container.begin ());

In other words: any time you want to have a nested subordinate type name in the template, you need to put the TypeName keyword in front of it. Of course he typename can only be used in this respect, other non-nested subordinate type names on TypeName are actually not allowed:

1 template<typename c>2void F (const// Note, This is not allowed in front of the C TypeName3     TypeName C::iterator iter);
There are two other special cases where TypeName is not allowed: TypeName can not appear in the base class list before the nested subordinate type name, nor in the member initialization list is often used to decorate the base class STL TypeName:
1 template<typename t>2void  Workwithiterator (iter iter)3{  4     typename std::iterrator_traits<iter>::value_type tmp (*Iter); 5 }

Here the iterator_traits mechanism is used to extract the iterator's value_type force, and the long variable declaration in the middle can actually be used as a typedef:

1 typedef typename STD::ITERRATOR_TRAITS<ITER>::VALUE_TYPE Value_type;

After that, you can use value_type and avoid too long declarative expressions.

Article 42: Understanding the dual meaning of TypeName

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.