C + + function template and class template instance parse _c language

Source: Internet
Author: User
Tags function definition int size

This paper gives a detailed example of C + + function template and class template, which helps readers to deepen their understanding of C + + function templates and class templates. The specific contents are as follows:

Generic Programming (Generic programming) is a programming paradigm that uses the type parameterization to manipulate multiple data types on the same code, and generics are generalized and reusable. Generic programming was originally born in C + + to implement the STL (Standard Template Library) of C + +.

Template (template) is the foundation of generic programming, and a template is a blueprint or formula for creating a class or function. For example, when using a generic type such as a vector or a generic function such as find, we provide enough information to convert the blueprint to a specific class or function.

A function template

A generic function template (function template) is a formula that can be used to generate a version of a function for a particular type or a specific value. The template definition starts with the keyword template, followed by a list of template parameters, with multiple template parameters (template parameter) separated by commas in the list. A template parameter represents a type or value that is used in a class or function definition.

1, type parameter

A template type parameter (type parameter) represents a type. We can consider the type parameter as a type descriptor, just like a built-in type or a class type descriptor. You must use the keyword class or typename before the type parameter:

Template <typename t>//TypeName and Class 
T function (t* p) 
{ 
  t tmp = *p;  The temporary variable type is T 
  //... 
  return tmp;  The return value type is t 
} 

The keyword TypeName is the same as class, but obviously TypeName is more intuitive than class, and it is more clear that the subsequent name is a type name.

The compiler instantiates the template type argument for us (instantiate) a specific version of the function, and a version is called an instance of the template (instantiation). When we call a function template, the compiler usually uses the function arguments to infer the template arguments for us. Of course, if the function has no parameters for the template type, then we need to specifically point out:

int a = ten; 
cout << function (&a) << Endl;   The compiler infers the template argument 
 
cout << function<int> (&a) << Endl based on the function arguments;  <int> indicates that the template parameter is int 

2. Non-type parameters

You can also define a nontype parameter (parameter) in a template, and a non-type parameter represents a value rather than a type. We specify the typename parameter by a specific type name instead of the keyword class or the word:

Shaping template 
template<unsigned M, unsigned n> 
void Add () 
{ 
  cout<< m+n << endl; 
} 
 
Pointer 
template<const char* c> 
void func1 (const char* str) 
{ 
  cout << C << "" << s TR << Endl; 
} 
 
Reference 
Template<char (&r) [9]> 
void Func2 (const char* str) 
{ 
  cout << R << "" ;< str << endl; 
} 
 
function pointer 
template<void (*F) (const char*) > 
void func3 (const char* c) 
{ 
  F (c); 
} 
 
void print (const char* c) {cout << C << endl;} 
 
Char arr[9] = "template";  global variable with static lifetime 
 
int main () 
{ 
  add<10, 20> (); 
  Func1<arr> ("pointer"); 
  Func2<arr> ("reference"); 
  Func3<print> ("template function pointer"); 
  return 0; 

When instantiated, the untyped parameter is overridden by a user-supplied or compiler-inferred value. A parameter that is not a type can be an integer or a pointer or reference to an object or function: an argument bound to a shape (not a type parameter) must be a constant expression, and an argument bound to a pointer or reference (not a type parameter) must have a static lifetime (such as a global variable), and the normal local variable cannot be Or a dynamic object is bound to a pointer or a referenced untyped parameter.

Second, class template

Accordingly, the class template (class template) is the blueprint used to generate the class. Unlike a function template, the compiler cannot infer a template parameter type for a class template, so we must explicitly provide a template argument. Like a function template, a class template parameter can be either a type parameter or a non type argument, and this is no longer discussed here.

Template<typename t> 
class Array {public 
: 
  Array (T arr[], int s); 
  void print (); 
Private: 
  T *ptr; 
  int size; 
}; 
 
class template external definition member function 
template<typename t> 
array<t>::array (T arr[], int s) 
{ 
  ptr = new t[s];< C15/>size = s; 
  for (int i=0; i<size; ++i) 
    ptr[i]=arr[i]; 
} 
 
Template<typename t> 
void Array<t>::p rint () 
{for 
  (int i=0; i<size; ++i) 
    cout < < "" << * (ptr+i); 
  cout << Endl; 
} 
 
int main () 
{ 
  char a[5] = {' J ', ' a ', ' m ', ' e ', ' s '}; 
  Array<char> Chararr (A, 5); 
  Chararr.print (); 
 
  int b[5] = {1, 2, 3, 4, 5}; 
  Array<int> Intarr (b, 5); 
  Intarr.print (); 
 
  return 0; 
}

member functions for class templates

Like other classes, we can define its member functions either inside the class template or outside of the class template. member functions that are defined outside the class template must start with a keyword template, followed by a list of class template parameters.

Template <typename t> 
return_type class_name<t>::member_name (parm-list) {} 

By default, for an instantiated class template, its member functions are instantiated only when they are in use. If a member function is not used, it is not instantiated.

Class templates and friends

When a class contains a friend declaration, the class is not related to whether the friend is a template or not. If a class template contains a friend that is not a template, the friend is authorized to have access to instances of all templates. If the friend itself is a template, the class can authorize instances of all friend templates, or it can only authorize specific instances.

A predecessor declaration that uses the 
Template<typename t> class Pal when declaring a particular instance of a template as a friend; 
 
Generic class 
C { 
  friend class pal<c>;//Pal with Class C instantiation is a friend of C 
  template<typename t> friend class Pal2 ; Pal2 all instances are friends of C, without the need for a predecessor declaration 
}; 
 
Template class 
Template<typename t> class C2 { 
  //C2 Each instance will be declared as a friend with a Pal that is instantiated with the same type, one-to-one relationship 
  friend class pal<t> ; 
  All instances of Pal2 are friends of each instance of the C2, without the need for a predecessor declaration 
  template<typename x> Friend class Pal2;  
  Pal3 is a generic template class, which is the friend 
  friend class Pal3 for all instances of C2 
; 

Static members of the class template

A class template can declare a static member. Each instance of a class template has its own unique static member object, and for a given type X all objects of the class_name<x> type share the same static member instance.

Template<typename t> 
class Foo {public 
: 
  void print (); 
  //... Other Operations 
private: 
  static int i; 
}; 
 
Template<typename t> 
void Foo<t>::p rint () 
{ 
  cout << ++i << endl; 
} 
 
Template<typename t> 
int foo<t>::i = 10;///initialized to 
 
int main () 
{ 
  foo<int> F1; 
  foo<int> F2; 
  Foo<float> f3; 
  F1.print ();  Output one 
  f2.print ();  Output 
  f3.print ();  Output one return 
  0; 
}

We can access the static object of a class template through a class-type object, or we can use the scope operator (::) to access the statically member directly. Similar to other member functions of a template class, a static member function is instantiated only when it is used.

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.