C++ generic programming

1. Template introduction

Generic programming: refers to the direct application of "function templates or class template library programs written using templates" for programming. In specific use, the programmer only needs to provide the type or value to the library function or class template used. Templates are the foundation of generic programming. For example, programming using containers and iterators in the standard template library is generic programming.

Template function: "Template function" emphasizes functions, and functions are implemented using templates.

Function template, "function template" emphasizes the template, and the template realizes the function of the function.

2. General formula of class template and function template

①Function template: template<class or typename template parameter name,...> returns the type function name (parameter list) {...}.

如:template<class T>void f(T a){T i;}

②Class template: template<class or typename template parameter name,...>class class name{...}. The class template must use the display template arguments to create the object.

如:A<int,double> ma;

3. Understand the template

① The template starts with the keyword template, and angle brackets <> are added after it.

②Template parameter: When declaring or defining a template, the angle brackets are the template parameter, and its form is "class or typename template parameter name". For example, template<class T>void f(); where T is the template parameter, and multiple template parameters are separated by commas. Note: The template parameter list cannot be empty.

③Template argument: Corresponding to the template parameter, it is used to pass to the template parameter to determine its value. The value here may be a certain type, or it may be a specific value, rather than a specific value in the traditional sense. The numerical value. If the template parameter represents a certain type, the template actual parameter is a specific type, which can be a custom type (class type), built-in type (int), or even a class template type.

 

4. Modify the position of template keywords

① The keywords that modify the template (such as friend, inline, const, extern, virtual, static, etc.) should be located after template<template parameter list>. For example, template<class T> static void f(); declare f as a static function;

②The template defaults to external links. Function templates can be internal links, that is, they can be decorated with static. For example, template<class T>static void f(){};

③The inline function template needs to be explicitly specified using the keyword inline (unless it is inline, such as located inside a class).

Guess you like

Origin blog.csdn.net/weixin_41882459/article/details/114012552