I will also talk about the c ++ template (1) and the c template.

Source: Internet
Author: User

I will also talk about the c ++ template (1) and the c template.

In c ++, programmers can use templates to write code irrelevant to types, improve source code reuse, and use it appropriately, greatly improving development efficiency. Previously, you can use the macro-current template function, but the template is more secure and clear. When writing template-related code, we use two keywords: template and class (or typename). there is basically no difference between class and typename.

1. Function Template

In essence, a function template implements code for the same algorithm of different types. Its basic usage can be as follows:

 template <class TYPE ,class TYPE,......>

 ReturnValue function(Argments)

 {

 // code

 }

HereTemplate <class TYPE, class TYPE,...>The code is declared as a template ." <> "Templates are provided.Type parameterWhen this code is used, the compiler generates an instance based on the actual type used. You can use the type parameter in the following function template,Returnvalue, arguments, localVariable can all use type parameters. The following is a simple function template example:

 1 template <class T> T foo(T& lhs,T& rhs) 2 { 3     T tmp = lhs; 4     lhs = rhs; 5     rhs = tmp; 6     return lhs>rhs?lhs:rhs; 7 } 8  9 int main()10 {11     int a(5),b(10);12     cout << foo(a,b) << endl;13     cout << "a=" << a << endl;14     cout << "b=" << b << endl; 15 16     string c("hello"),d("world");17     cout << foo(c,d) << endl;18     cout << "c=" << c << endl;19     cout << "d=" << d << endl;20 }

Rows 1-5 are the basic usage of the function template. The function of the foo () function is to exchange two parameters and return a large value. However, the foo () function does not care about the parameter type. When we use the foo template in main (), both int and string types can be used to get the expected results, while the foo Code only writes one copy, not for int and string.

This is the output result:

10
A = 10
B = 5
World
C = world
D = hello

2. function templates in the class

The class contains a member function template, which is similar to the previous one, but only limits the scope. To be honest, this situation should be more common than the previous one, because c ++ is an object-oriented language, and the functions we define usually need to be defined in the class, minimize the use of global functions. Of course it's a little too far away. Write a small example to explain the usage:

class X{public:   template <class T> 
  void mf(T* t) {}};int main(){ int i; X* x = new X(); x->mf(&i);}

This is basically the same as the first case.

3. Simple class templates

The syntax wildcard for defining a class template can be as follows:

template<class TYPE,class TYPE...>

class CLASSNAME

{

  //members.

};

template<class TYPE,class TYPE...>

ReturnValue CLASSNAME<TYPE,TYPE...>::function (Arguments)

{

  //code.

}

The usage of a class template is similar to that of a function template. Note that when the declaration and definition are separated, it is not enough to specify the Template Name when defining a member function, to add a type, only such restriction will be a class name rather than a template. For example:

template <class T>class Bar {    void foo();};template<class t>void Bar<T>::foo(){    //}

Void Bar <T>: foo () is important, which is one of the most common errors in using templates. Bar is only the template and Bar <T> is the class name.

4. function templates in class templates

The member functions in the class can also be a template, which forms a hierarchical relationship. Note that when defining a member function template, you must consider the hierarchical relationship between the templates based on the previous example. For example, a piece of code:

 1 template<typename T> 2 class X 3 { 4 public: 5    template<typename U> 6    void mf(const U &u); 7 }; 8  9 template<typename T> 10 template <typename U>11 void X<T>::mf(const U &u)12 {13 }14 15 int main()16 {17 }

Two types of parameters T and U are defined in rows 9-10. U is the type parameter of the member function template. If 11 rows are written as follows:

void X<U>::mf(const T &u)

An error is reported.

Note that:

Member template functions cannot be virtual functions and cannot override virtual functions from a base class when they are declared with the same name as a base class virtual function.

When you declare a function with the same name as a base-class virtual function, the member template function cannot be a virtual function and cannot be rewritten from the base-class virtual function.

The difference between the two codes is better.

5. nested class templates in common classes

Nested class templates are declared as class templates within the scope of the external class. They can be defined inside or outside the closed class. In layman's terms, the scope of the nested class template is its class, and the definition of the nested class can be defined outside ., The following is a simple example of the nested classes on msdn:

 1 #include <iostream> 2 using namespace std; 3  4 class X 5 { 6  7    template <class T> 8    struct Y 9    {10       T m_t;11       Y(T t): m_t(t) { }   12    };13 14    Y<int> yInt;15    Y<char> yChar;16 17 public:18    X(int i, char c) : yInt(i), yChar(c) { }19    void print()20    {21       cout << yInt.m_t << " " << yChar.m_t << endl;22    }23 };24 25 int main()26 {27    X x(1, 'a');28    x.print();29 }

Struct Y is a class template nested in class X. In class X, template Y generates two types of instances, namely, Y <int> and Y <char>. All subsequent operations can regard Y <int> and Y <char> as common class types.

6. nested class templates in class templates

Similar to the previous case, the outer class is a class template, not a specific class type. In this case, it is worth noting that:

When nested class templates are defined outside of their enclosing class, they must be prefaced by the template parameters for both the class template (if they are members of a class template) and template parameters for the member template.

When a nested class template is defined externally in its closed class, it must start with the template parameters of the class template (if they are members of the class template) and the template parameters of the member template. ------ MSDN Manual

The translation is also relatively easy to understand, but it is also easy to understand if you read it several times: when defining Nested classes, we need to consider the situations mentioned in section 3rd that need attention ,":: "The domain operator acts on the class rather than the template. Therefore, when defining Nested classes externally, we should not only add template parameters after the outer class template, but also make the form (not instantiated) into a class, A template parameter must be added to a nested class to form a class.

 1 #include <iostream> 2 using namespace std; 3  4 template <class T> 5 class X 6 { 7    template <class U> class Y 8    { 9       U* u;10    public:11       Y();12       U& Value();13       void print();14       ~Y();15    };16 17    Y<int> y;18 public:19    X(T t) { y.Value() = t; }20    void print() { y.print(); }21 };22 23 template <class T> 24 template <class U>25 X<T>::Y<U>::Y()26 {27    cout << "X<T>::Y<U>::Y()" << endl;28    u = new U();29 }30 31 template <class T> 32 template <class U>33 U& X<T>::Y<U>::Value()34 {35    return *u;36 }37 38 template <class T> 39 template <class U>40 void X<T>::Y<U>::print()41 {42    cout << this->Value() << endl;43 }44 45 template <class T> 46 template <class U>47 X<T>::Y<U>::~Y()48 {49    cout << "X<T>::Y<U>::~Y()" << endl;50    delete u;51 }52 53 int main()54 {55    X<int>* xi = new X<int>(10);56    X<char>* xc = new X<char>('c');57    xi->print();58    xc->print();59    delete xi;60    delete xc;61 }

Finally, it is worth noting that, as in the fourth case, the nested class also has a hierarchical relationship with the template parameters of the outer class. Generally, two rows are written:

Template <class T>
Template <class U>

T is treated as the template parameter of the outer class, and U is treated as the template parameter of the nested class. I have read some books, which are easy to distinguish between the indentation form:

Template <class T>
Template <class U>

I have a lot of knowledge about templates. I have no energy to write them for the moment. I will write them tomorrow. Which of the following are not in place? Please refer to the official correction. Thank you. I QQ: 5435620. EMAIL: baixiangcpp@gmail.com.

Related Article

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.