How to Use templates in C ++

Source: Internet
Author: User

Starting from knowing nothing about the use of backends. template in modern c ++ design, we need to thoroughly understand the C ++ template if the determination of the work has already been done. What's more, today, when implementing B-tree, it is suffering from the template compilation problem repeatedly. I have strengthened my belief in reading this book C ++ template. The complete guide. Although I used to know something about this topic, what is special, partial special, parameter deduction, and so on. However, it is also necessary to take a systematic look. Of course, I agree with nocolai very much when I study here. practicality is king because I cannot become a scientist even if I am not a scientist :).

At the beginning of this study, I would like to repeat the classic topic: Why templates?

The reason is simple. When designing a data structure or algorithm, you need to describe different data types but similar behaviors. For example, if you have a quicksort, you want it to be able to sort int, float, STD: string.

You have many methods: First, you can implement three quicksort parameters: int [], float [], STD: String [], which can work. However, the problem is obvious. If the int sorting you implemented for the first time is wrong, you are finished. You must change all three implementations. If this code is maintained by yourself, you can barely maintain it. If many people maintain it, others may not know that such a history is in the code. Therefore, this solution is inappropriate.

The second method is more common, namely, void * or object to replace the specific type. Every time I implement a container, the content of push_back is object & or void *, this object & or void * is used to replace the specific type. The advantage is that you do not need to rewrite the three-part code, but the problem is very obvious. After using void *, You need to convert the type, and the original type information is lost. In this case, a float is also converted into an int and added to the sort queue, which does not show your thoughts. If the same problem exists in object &, if the objecta of the data to be sorted inherits both objectb and objectc, and both parent classes are subclasses of the object, that's the annoying diamond !!! Simply put, this kind of requirement to enforce sorting parameters cannot be well guaranteed in terms of maintainability.

Of course, when templates are not applied, macro definitions are also used to replace templates. Let's take a look at those familiar figures:

#define SWAP(a, b)  {                   \                          a ^= b;         \                          b ^= a;         \                           a ^= b;         \                      }   #define MAX(a, b) ((a) < (b) ? (b) : (a))  

If not those C/C ++ masters constantly strengthen the max or min writing method, I think this "Stupid replacement mechanic" will definitely drive a lot of people crazy. Yes, this macro definition is too prone to errors. In C ++, it is constantly replaced, simple functions become inline, and values define program enum. In short, the tone of C ++ is to forget the macro and the pre-definition.

So at this moment, both C # and Java are pushing the template. Why do we not need a c ++ template?

The pressure on macros (preprocessing) is too deep, so the first thing after the template is available is to define the template function to replace those Max and Min. The author is also happy with this. Next I will immediately look at the implementation of a simplest template function max:

template <typename T>  inline T const& max (T const& a, T const& b)  {      // if a < b then use b else use a      return  a < b ? b : a;  } 

If you try to explain it one by one, it is like this: Template indicates that this is a template function. <> the template parameter area is specified, and typename indicates that the following parameter is a type name, t indicates a broad type, which can be used to specify all types (INT, float, STD: string ). All of these constitute the most basic template function. It must be noted that due to historical reasons, typename can be replaced by class. (Many of them are described using class ). Of course someone asked me if struct is okay. Of course the answer is no!

After understanding the definition of this function, the second step is to explore how to call it. Here are several examples:

max(1,2 );      // max<int>  max('1','2');       // max<char>  max(1, 2.5 );       // compile error  max<double>(1,2.5 );  // max<double>  

The first and second calls have no problems, just like common function calls. Of course, their calls can be successful. However, when the third call occurs, the compiler reports an error 'const T & MAX (const T &, const T &)': template parameter 't' is ambiguous. We can see that there is a problem with the parameter type here, and the two parameters have different types. The compiler does not know how to specify t because it is an int or a double. Note that the compiler requires an exact type, so it will not take the initiative to convert it to you. Not from int32 to int16. So here you need to explicitly tell the compiler how to do it. This is the fourth call.Max <double> (1, 2.5 );Or you can forcibly convert parameter 1 to double and then call it, for exampleMax (static_cast <double> 1, 2.5).

Furthermore, let's take a look at how the compiler helps us implement these calls. To put it simply, the compiler uses the method of calling what type exists, and I will generate a bunch of Max code corresponding to what type. For exampleMax (1, 2 );When the call comes, I will generate such code for you:

inline int const& max (int const& a, int const& b)   {      return  a < b ? b : a;  } 

It is to use int to replace the original t to generate specific types of code, so that the original programmer needs to write the function for different types of versions and then hand it over to the compiler. The process in which the compiler generates the corresponding function code for different types is called Instantiation. it is a coincidence that the instantiation in OO is the same word. Of course, the meaning is definitely different ). Next we can look at a complex example:

#include "stdafx.h"  #include <iostream>  #include <cstring>  #include <string>  // maximum of two values of any type  template <typename T>  inline T const& max (T const& a, T const& b)  {      return  a < b  ?  b : a;  }  // maximum of two pointers  template <typename T>  inline T* const& max (T* const& a, T* const& b)  {      return  *a < *b  ?  b : a;  }  // maximum of two C-strings  inline char const* const& max (char const* const& a,                                 char const* const& b)  {       return  std::strcmp(a,b) < 0  ?  b : a;  }  int _tmain(int argc, _TCHAR* argv[])  {      int a=7;      int b=42;      ::max(a,b);      // max() for two values of type int      std::string s="hey";      std::string t="you";      ::max(s,t);      // max() for two values of type std::string      int* p1 = &b;      int* p2 = &a;      ::max(p1,p2);    // max() for two pointers      char const* s1 = "David";      char const* s2 = "Nico";      ::max(s1,s2);    // max() for two C-strings            char* a1 = "CY";      char* a2 = "HY";      ::max(a1,a2);      return 0;  }  

This is a complete example running under vs2005. The difference here is that the template function has different overloaded versions. Before instantiation, we need to find the most suitable function call for different types, such as calling Max (, b); When A and B are all int, the compiler finds that the first max function is the most matched version with value as the parameter, so the int version of the first function will be developed for this instance. Note that the matching process here is called deduction ). The basic principle of deduction is to first match non-template functions that coexist, and find the closest template function if they fail. For example, max (S1, S2); matches the max function of the version of const char *, while Max (a1, a2 ); is the second Max function, that is, the version of the type parameter as the pointer.

So far, it is still a bit of flowers and flowers. The smart compiler can do everything we want. Max's performance is surprisingly consistent with what we expected. Of course, one thing we have to mention is the surge of calm. See the following example:

#include <iostream>  #include <cstring>  #include <string>  // maximum of two values of any type (call-by-reference)  template <typename T>  inline T const& max (T const& a, T const& b)  {      return  a < b  ?  b : a;  }  // maximum of two C-strings (call-by-value)  inline char const* max (char const* a, char const* b)  {       return  std::strcmp(a,b) < 0  ?  b : a;  }  // maximum of three values of any type (call-by-reference)  template <typename T>  inline T const& max (T const& a, T const& b, T const& c)  {      return max (max(a,b), c);  // error, if max(a,b) uses call-by-value  }  int main ()  {      ::max(7, 42, 68);     // OK      const char* s1 = "frederic";      const char* s2 = "anica";      const char* s3 = "lucas";      ::max(s1, s2, s3);    // ERROR  }  

We can see that if these template parameter types do not match, the problem is great. We can see max (, 68); there is no problem, the max functions of the three parameters match the first max function. There is no problem here. We all use reference semantics. But to max (S1, S2, S3);, the max (a, B), c); matches the max version of const char *. In this way, the return value of Max is changed from reference to stack value. Although the comment here writes error, in fact, only one returning address of local variable or temporary warning will be reported in vs2005! Attention should be paid to the packages that take error as the condition for judgment. In fact, such warning will also be fatal. Therefore, smart compilers do not always give us peace of mind.

After talking about function templates in a rough way, we must talk about the most important class templates. Because it is the beginning, it must be clear:

#include <vector>  #include <stdexcept>  template <typename T>  class Stack {    private:      std::vector<T> elems;     // elements    public:      void push(T const&);      // push element      void pop();               // pop element      T top() const;            // return top element      bool empty() const {      // return whether the stack is empty          return elems.empty();      }  };  template <typename T>  void Stack<T>::push (T const& elem)  {      elems.push_back(elem);    // append copy of passed elem  }  template<typename T>  void Stack<T>::pop ()  {      if (elems.empty()) {          throw std::out_of_range("Stack<>::pop(): empty stack");      }      elems.pop_back();         // remove last element  }  template <typename T>  T Stack<T>::top () const  {      if (elems.empty()) {          throw std::out_of_range("Stack<>::top(): empty stack");      }      return elems.back();      // return copy of last element  }  

The above is the implementation of the most basic template class given by the author. Like the template function, you can see the familiar template keyword, the type identifier of the <typename T> template parameter. The benefit of this implementation is that it not only tells you to declare a template class, but also shows you to implement the interface of this template class. We can see that, except for this stack <t>: This type identifier is here, it is the same as a template function .. Through this example, we can find that if the template class is used, STD: vector <t> elems; so if we want to use this stack class, the same is true, you can also use stack <t> ELEM; to declare that t can be int, float, STD: string... if it is a function call, it is exactly the same as the call of a common class. It can be said that this implementation is still not surprising.

It is worth noting that we often see in mature class libraries that template parameters are also template class definitions, such as: typedef functor <product *, seq <int, int> createfunctor; this seems dull. It is nothing more than seq <int, int> as the second template parameter of functor. But in fact, there must be a space after this int>! Without this space, two consecutive greater than signs> are mistaken by the compiler as> operators. However, the point is that !!! In vs2005, the compiler has accepted such a definition. Even if there is no intermediate space, the compiler can still understand it correctly, if you want to write code that can be run in each compiler, we recommend that you add spaces in the middle. (The compiler is always changing, but the book has not changed. It is also a normal thing to keep up with the times)

This is generally the case. When there is no template, we all hope that such a universally established thing can reduce our work. It is really possible to have this thing in the future. I found that such code is for all types. If I need to customize some types. this method is also called specialization ). here is an example of the stack class being STD: String special.

#include "stack1.hpp"  template<>  class Stack<std::string> {    private:      std::deque<std::string> elems;  // elements    public:      void push(std::string const&);  // push element      void pop();                     // pop element      std::string top() const;        // return top element      bool empty() const {            // return whether the stack is empty          return elems.empty();      }  };  void Stack<std::string>::push (std::string const& elem)  {      elems.push_back(elem);    // append copy of passed elem  }  void Stack<std::string>::pop ()  {      if (elems.empty()) {          throw std::out_of_range                  ("Stack<std::string>::pop(): empty stack");      }      elems.pop_back();         // remove last element  }  std::string Stack<std::string>::top () const  {      if (elems.empty()) {          throw std::out_of_range                  ("Stack<std::string>::top(): empty stack");      }      return elems.back();      // return copy of last element  }  

Here, a template <> class Stack <STD: String> header is used to authenticate the STD: string type for the Stack class. in the original article, there is a saying that if you want to specialize in a class, you must specialize in all functions. of course, it must be noted that the function you will use must be specially optimized, if this top function will not be used in the future. the compiler won't say that you are not completely specialized. in fact, if you need a small scope of specialization, it is also possible to simply develop a function. for example, you can choose to write the template <> void stack <STD: String> POP (). Note that the template here <> can also be left empty.

So far, we have seen only one template parameter for the template class. Of course, we can have multiple template parameters. Here we will first look at the stimulus :)

template     <        class AbstractProduct,        typename IdentifierType,        typename CreatorParmTList = NullType,        template<class> class EncapsulationPolicy = SimplePointer,        class CreationPolicy = AlwaysCreate,        template <typename , typename> class EvictionPolicy = EvictRandom,        class StatisticPolicy = NoStatisticPolicy,        template<typename, class> class FactoryErrorPolicy = DefaultFactoryError,        class ObjVector = std::vector<AbstractProduct*>     >  class CachedFactory :             protected EncapsulationPolicy<AbstractProduct>,            public CreationPolicy, public StatisticPolicy, EvictionPolicy< AbstractProduct * , unsigned >  

This is an ordinary definition in Loki. It means that the class template can have multiple template parameters. It can also have default parameters, just like a common function definition. this example may not be very suitable. It should be said that there are not only parameters, but also template parameters of the type. it is not a typename T type parameter. For example, you can have an int parameter. this definition is also possible: Template <typename T, int size> class Stack; this size can be left to the stack class users (the key is the compiler decision) the size of the stack. of course, can int be short or long? In principle, the integer type is acceptable, but float and double are not allowed until today.

Back to the theme of specialization, Is it difficult for you to have so many parameters? It doesn't matter. c ++ template also provides a feature called partial specialization, which means you can customize one or more template parameters instead of all parameters. forgive me for my laziness. This is a special example:

template<class T, class T2, class T3>class Stack  {  public:      void f1()      {      }  };  template<class T> class Stack<T, int, long>  {      public:      void f1()      {      }  };  

Of course, it is similar to theme-making, but not many are selective.

Well, today we can say so much about it. Now this book looks flat, but it still doesn't seem to make any changes. however, in the process of in-depth development, it is still slowly revealing his depth, which is totally different from <modern c ++ design>, but it also has a special flavor.

 

From: http://blog.csdn.net/hhygcy/archive/2009/02/20/3914287.aspx

 

 

 

 

 

 

 

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.