Valid C ++ clause 42 and valid clause 42

Source: Internet
Author: User

Valid C ++ clause 42 and valid clause 42

In this section, we will discuss the differences between the class keyword and the typename keyword, and the impact on the template function.
The following code:

template<class T>T getValue1(T m){    return m * 2;}template<typename T>T getValue2(T m){    return m * 2;}

In the above Code, the roles of class and typename are the same and there is no difference. Therefore, programmers can use class or typename according to their personal habits when declaring a template. However, in some cases, only typename can be used 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; // a1 = 0; return a1;} int main () {Defalut d; cout <getValue (d); return 0 ;}

C ++ specifies that only typename and class can be added to the comment line above.
Why does an error occur when the typename program is not added? Let's imagine the following code:

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

Now let's take a look at the call Defalut: a for two classes with the same name. One returns the int type and the other returns the integer value.
In the template, T: a is used to determine whether the return value or the type. For C ++, typename, without the prefix keyword, is considered as the return value, such as T:, returns a static value. If the keyword typename is added, it is considered to be the return type, for example, typename T: a, and a nested type is returned.
Nested type refers to the type defined in the class or other structures.

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.