Effective C + + clause 43

Source: Internet
Author: User

In this section we discuss the difference between the class keyword and the TypeName keyword and the effect on template functions.
The following code:

T>T getValue1(T m){    return2T>T getValue2(T m){    return2;}

In the above code, class and TypeName are the same, without any difference, so programmers can use class or typename when declaring templates, depending on their personal habits. But in some cases you can only use TypeName instead of class.

The following code:

 #include <iostream>  using  namespace  STD ; class  Defalut{public : typedef  int  A;}; template  <typename  t> int  getValue (T m) {typename  t::a a1;//if not typename compile error  a1 = 0 ; return  A1;}    int  Main () {Defalut D;    cout  <<getvalue (d); return  0 ;}  

C + + stipulates that the above comment line can only be added typename, not add Class
Why not add the TypeName program will make a mistake, let's now imagine that the following code form is compared:

classDefalut{public:    typedef int a;};classDefalut{public:    static int a;};Defalut::a;

Let's take a look at the call defalut::a of the two classes with the same name, one return type int, the other returns an integer value.
So that is, in the template to determine whether the t::a is a return value or type, for C + +, without the predecessor Keyword TypeName is considered to be a return value, such as T::A, is considered to return a static value. The TypeName keyword is considered to be a return type, such as TypeName T::a, which is considered to return a nested type.
Nested types are types defined in class classes or other structures.

Effective C + + clauses

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.