Template and generic programming in C + +

Source: Internet
Author: User
Tags strcmp variadic

Directory
      • Define a generic template
      • Template Special and partial localization
      • Template instantiation and matching
      • Variable parameter templates

 Generic programming refers to writing code independently and in any type of way. Generic programming and object-oriented programming are dependent on some form of polymorphism. Object-oriented programming polymorphism is applied at run time to classes that have inheritance relationships, and a piece of code can ignore the difference between a base class and a derived class. In generic programming, the code you write can be used as multiple types of objects. The polymorphism that object-oriented programming relies on is called run-time polymorphism, and the polymorphism that generic programming relies on is called compile-time polymorphism or parametric polymorphism.

1 Template definition 1.1 function template
    • function template Invocation method. In the event of a call to a function template, the parameter deduction is not shown, and the implicit template argument call called the function template (implicit invocation) shows the template parameter instead of the parameter deduction, which is called the display template argument call of the function template when the function template is called (the call is displayed). The display template argument invocation is necessary if the argument deduction is unsuccessful.
    • function templates and function overloads. function template is actually to establish a general function, its function type and formal parameter type is not specified, with a virtual type to represent, general function of the same function can be used to replace the template, not necessarily with a number of functions. There must be at least one difference in the number of arguments, parameter type, or parameter order of an overloaded function, and the function return value type can be the same or different, and the function body can be the same or different.
Template<typename t>int getmaxval (constconst t& T2) {     return T1 < T2? t2:t1;}
Class 1.2 Templates
    • A class template is also a template, so you must start with a keyword template, followed by a template parameter list
    • In addition to the template parameter list, the definition of a class template looks similar to any other class. Class templates can define data members, function members, and type members, or you can use Access labels to control access to members, as well as to define constructors and destructors, and so on.
    • In contrast to calling a function template, when using a class template, you must explicitly specify an argument for the template parameter, and there is no argument deduction for the formal parameters of the class template .
Const  - ; template<class t>class  stack{private:    T elements[ MAXSIZE];  Public :     // others};
1.3 Template Parameters
    • Type template parameter: The type parameter is made up of the closing word class or typename followed by specifier, such as Template<class t> void Getmaxval (const t& a,const t& b) {} where T is a type parameter and the name of the type parameter is self-determined by the user.
    • non-type template parameter: The template's non-type parameter is the built-in type parameter, such as Template<class T, int x> greaterthanx (const t& a), where int X is a non-type template parameter. A non-type parameter is a constant value inside the template definition, meaning that the non-type parameter is constant inside the template. Non-type template parameters are limited and generally an integral type, which can be a constant integer (including an enumeration type) or a pointer to an externally linked object. for non-type template parameters. The default parameters for the
    • template. for the type parameters of a function template. Both the function template and the class template can provide default parameters for the template's non-type parameter. The default value of the class template type parameter is the same as the default for the function, and if there are more than one type parameter, all template parameters that are set from the first parameter to the default value are set to a default value. The type parameters of the class template are in the default form: Template<class T1, Class t2=int> class a{}, the default value of type int for the second template type parameter T2, and when a member of a class is defined outside of a class template After the formal parameter list should omit the default formal parameter type. such as template<class  T1, Class t2=int> class a{public:void H ();}; The definition method is Template<class t1,class t2> void A<t1,t2>::h () {}
 template<typename t,int  X = 5  >inline  const  t& a) { return  a >=< Span style= "color: #000000;" > X;} Std::cout  << Greaterthanx (10 ) << Std::endl; 
template<class T,int maxsize=>class  Stack {private :    T Elements[maxsize];  Public :     // others};
2. Template specificity and biasing sometimes for the sake of a specific type, the template needs to be specialized, that is, special processing. For example, the Stack class template is for the bool type, because the bool type actually requires only one bits, which can be stored, using one word or one byte as a waste of storage space. The specificity must be done under the same namespace, and special class templates can also be customized, but class templates can be biased and fully specific, and function templates will only be fully specific. The template's partial specificity refers to the need to be specific to some, but not all, parameters of the template. Strictly speaking, function templates do not support biasing, but because functions can be overloaded, it is possible to achieve a similar effect to class template biasing. When the template is instantiated, it will first match the specific version of the template parameter that best matches it. 3 template instantiation and matching rules

implicit instantiation of the 3.1. When using template functions and template classes, there is no entity for the specified type of template function and template class, and the compiler implicitly generates the template function or the entity of the template class as an implicit instantiation of the template based on the specified type parameter. Implicit instantiation of a function template refers to a function template that is instantiated when a function call is made, if no matching function is found, and if the argument type deduction can be successful. The implicit instantiation of a class template refers to instantiating a template when using a template class.

2.2 Display instantiation . Display instantiation is also known as external instantiation. Instantiate a function template when no function call occurs, or instantiate a class template as a template display instantiation when the class template is not applicable

2.3 Matching rules 4. Variable parameter templates

The variadic template is one of the new features of C++11, which is highly generalized to parameters and can represent 0 to any number of arguments of any type. The variable template parameter is preceded by an ellipsis, and the parameter with the ellipsis is called the "parameter Package", which contains 0 to N (n>=0) of template parameters. We cannot directly obtain each parameter in the parameter package args, only by expanding the parameter package to get each parameter in the parameter package, which is a key feature of using the variable template parameters. The variable template parameters and the Normal template parameter semantics are consistent, so it can be applied to functions and classes, variable template parameter functions and variable template parameter classes, however, the template function does not support the partial localization, so the variable template parameter functions and variable template parameter classes expand variable template parameters are not the same method.

4.1 Variable template parametric functions and parameters expansion

L The recursive function expands the parameter package. To expand a parameter package with a recursive function, you need to provide a function for the expansion of a parameter package and a recursive termination function, which is used to terminate the recursion.

L Expand the parameter pack by commas

4.2 Variable template parameter classes and parameters expansion

The parameter package expansion of variable parameter template class is different from that of variable parameter template function, the parameter package expansion of variable parameter template class needs to be expanded by template special and inheriting mode, and the expansion mode is more complex than the variable parameter template function. Specific reference http://www.cnblogs.com/qicosmos/p/4325949.html

The Variadic template class is a template class with variable template parameters, such as the Ganso std::tuple in c++11 is a mutable template class, which is defined as follows:

template< class ... Types >
Class tuple;

This variable-parameter template class can carry any number of template parameters of any type:

Std::tuple<int> TP1 = std::make_tuple (1);
Std::tuple<int, double> TP2 = std::make_tuple (1, 2.5);
Std::tuple<int, double, string> TP3 = std::make_tuple (1, 2.5, "");

The variable parameter template can have 0 template parameters, so the following definitions are also valid:

std::tuple<> TP;

Reference:

1. Template specificity and chip localization

2. The beauty of generalization--c++11 the magic of variable template parameters

3. Template parameters

Template Specializations

Sometimes a unified template does not solve all the parameter problems, such as a unified template can not be compiled, not properly instantiated, the output is problematic

Template Special: function template Specialization, class template specialization

1. function Template Special

For example : Defines a compare template function that defines "<" with comparisons, such as int,double and custom types.

A. in order to handle string constants, the Compare ("HI", "com")overloads the

template<unsigned n,unsigned m>int Compare (const char (&P1) [N],const char (&p2) [M])
Note: When comparing string lengths, GCC 4.83 is considered to be ambiguous with int compare (const t& v1,const t& v2) and cannot be instantiated correctly, compiled without

test.cpp:In function ' int main () ':
Test.cpp:45:34:error:call of overloaded ' compare (const char [6], const char [6]) ' is ambiguous
Cout<<compare ("Hello", "Hello") <<endl;
^
Test.cpp:45:34:note:candidates is:
Test.cpp:14:5: Note:int Compare (const t&, const t&) [With T = char [6]]
int compare (const t& v1,const t& v2)
^
Test.cpp:25:5: Note:int Compare (const char (&) [n], const char (&) [M]) [with unsigned int N = 6u; unsigned int M = 6U]
int compare (const char (&P1) [N],const char (&P2) [M])

B. in order to handle the string pointer cout<<compare (STR1,STR2) <<endl; we have customized int compare (const t& v1,const t& v2), Note The format of the special and the type of the parameter.

#include <iostream>#include<cstring>using namespacestd;template<typename t>intCompareConstt& v1,Constt&v2) {   if(V1&LT;V2)return-1; if(V2&LT;V1)return 1; return 0;}//notype template parameter//handle string Literals,that type is const char[]template<unsigned n,unsigned m>intCompareConst Char(&AMP;P1) [N],Const Char(&p2) [M]) {    returnstrcmp (P1,P2);}//Special version of compare to handle pointers//To character ArraysTemplate<>intCompareConst Char*Const& P1,Const Char*Const&p2) {    returnstrcmp (P1,P2);}intMain () {Const Char* str1="Hello"; Const Char* str2="Hello"; cout<<compare (1,2) <<Endl; //note:same string length lead to instantiate ambiguouslyCout<<compare ("Hello","Hell") <<Endl; Const char[] cout<<compare (STR1,STR2) <<Endl; return 0;}
2. Class template specificity
Template <classT>classcompare{ Public: BOOLisequal (t t1, T T2) {returnT1 = =T2;}}; intMain () {CharStr1[] ="Hello"; CharStr2[] ="Hello"; compare<int>C1; Compare<Char*>C2; cout<< C1. IsEqual (1,1) << Endl;//compare parameters of two int typescout << C2. IsEqual (str1, str2) << Endl;//Compare parameters of two char * types return 0;}
Template<>classcompare<Char*>//Special (char*)2 {3   Public:4     BOOLIsEqual (Char* T1,Char*T2)5     {6         returnstrcmp (t1, t2) = =0;//comparing strings using strcmp7     }8};

Template and generic programming in C + +

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.