C + + Template

Source: Internet
Author: User

In the template definition syntax, the keyword class functions exactly like TypeName.

What is a class template

If the data type of a data member in a class cannot be determined, or if the type of the parameter or return value of a member function cannot be determined, the class must be declared as a template

Class template definition

STEP1: Declaring templates

Three forms of declaration:
1. Basic template class
Template<class T1,class t2>
2. With default type parameters
Template<typename T3, TypeName t4=int>
3. With non-type template parameters
Template<class T5,int a>

STEP2: Defining classes

template<class t>class  test{private:    T N;     Const T i;     Static T-cnt;  Public :    Test (): I (0) {}    Test (T k);     ~Test () {}    void  print ();     operator+(T x);};

STEP3: When defining member functions in the class definition body, if there are template parameters in this member function, you also need to declare the template outside the body of the function and add "<T>" to the class name suffix in front of the function name.

template<class t>Test<t>::test (T k): I (k) {n=k;cnt++;} Template<class t>T Test<t>::operator+(T x) {       return n + x;}

STEP4: Initializes a const member and static member variable in the class definition body and requires a template declaration

template<class t>int test<t>::cnt=0;

What is a template class

A template class is a product of the instantiation of a class template.

What is a function template

Template<typename (or Class) t>t fuc (t X, t y) {    T x;     // ...}

What is a template function

The generation of template functions is the process of instantiating the type parameters of a function template

C + + Template

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.