Effective C + + clause 42

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.


For example, the following code:

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

In the code above. The function of class and TypeName is the same. No matter what the difference. So the program ape is able to use class or typename when declaring templates according to personal habits.

It is only in some cases that you can use TypeName instead of class.

For example, 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;//assumes that there is no TypeName compilation error  a1 = 0 ; return  A1;}    int  Main () {Defalut D;    cout  <<getvalue (d); return  0 ;}  

C + + stipulates that the gaze line above can only add typename, not add Class
Why not add the TypeName program will go wrong, we now imagine, for example, the following control code form:

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

Now let's look at the call of the two classes with the same name, a return type int, and a return integer value, defalut::a.
So that means that the t::a inference is the return value or type in the template. For C + +. Without the predecessor Keyword TypeName think it is the return value. such as T::a, feel the return of a static value.

Added the TypeName keyword to think of as a return type, such as TypeName T::a. Think of returning a nested type.
Nested types are types defined in class classes or other structures.

Effective C + + clause 42

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.