Data types bring trouble to program design and the solution
int maxt(int, int);
double maxt(double, double);
If there is a placeholderT
The ability to replace types simplifies the redundancy of writing code.
T maxt(T,T);
C++ templates
The template statement is as follows
template<typename T1, ...>
template
is the C++ keyword for template declarations, with pointed brackets for theTemplate parameter listtypename
Declaring keywords for type placeholders
template<typename T>
T maxt(T x, T y){
return (x>y)? x: y;
}
function template
existpre-compilestage, when a function template is called in a program, the compiler replaces the type placeholder with the actual type to generate the entity function
If the compiler can derive the required type of the template parameter from the function's real parameters, you may not pass in the template parameter
template<typename T>
T maxt(T x, T y){
return (x>y)?x:y;
}
int main(int argc, char* argv[]){
// std::cout<< maxt<int>(4,6)<< std::endl;
std::cout<< maxt(4,6)<< std::endl;
return 0;
}
class template
When declaring a class, use thetemplate
Just make a template declaration
template<typename T>
class Circle{
public:
Circle(T r);
}
If a member function is implemented outside of a class template, it must be declared as a function template
template<typename T>
Circle<T>::Circle(T r){}
When calling, you need to pass the specific type after the class name using pointed brackets
Circle<int> circle;
STL's template programming is not interested in object-oriented techniques, and it believes that excessive encapsulation of data by classes affects the efficiency of program execution
And to better manage the code, so the STL uses a lot of access-lessstruct
Class templates produced
Variable templates
Variable templates, extends the template to variables
as ifpi<T>
implementation
(coll.) fail (a student)T
because ofdouble
When you return the3.14
(coll.) fail (a student)T
because ofint
When you return the3
(coll.) fail (a student)T
because ofstring
When you return the"3.14"
maybe"pi"
New C++ standard's efforts to generalize design
auto and decltype
In C++11, theauto
keyword to derive the data type of the variableauto a=100;
auto
Types can be acquired either through the compiler's type-memory capabilities or thedecltype
The type hints to derive the
Using Type Memory to Derive Complex Types
auto
Currently has limited capabilities and only works on the system's built-in data types
For user-defined or complex types, the ability to derive them is only available once the compiler has gained enough experience
map<int,map<int,int>>::const_iterator iter1=();
auto iter2=();
Since the previous statement tells the compiler to()
The type of the second statement is processed, then the memory capability is utilized to automatically derive theiter2
types of
decltype
Expressions provide guidance on the type of return value of a derived function
The problem of the difficulty of determining the type of a variable generally arises with function return values, and C++11 can use thedecltype
Guidance on type derivation of function return values
When returning theauto
If you need the compiler to derive the type of the function's return value, you can use thedecltype
Guidance on the derivation
template<typename T, typename U>
auto Multiply(T t, U u)->decltype(t*u){
return t*u;
}
utilizationauto
as the type of function return value is calledauto return value placeholder
commander-in-chief (military)auto
Viewed as a datatype, theauto
is also a generalization, but without the keywordtypename
representations
and the actual type is not explicitly provided by the real parameter, but rather based on the historical memory associated with the type operation and the derivation ideas provided by the application program
Template parameters
Depending on the nature of the parameters, template parameters are categorized as type parameters, non-type parameters, and template-defined parameters.
type parameter
using keywordstypename
Parameters of the declaration
The type real parameters of the type parameter are included:
- Types built into the system
- User-defined data types
- The compiler has just learned the class template entity
- leave it (to sb)
typename
Defined type aliases
untyped parameter
C++ allows ordinary variables or objects to be defined in template parameter lists, such astemplate<typename T, int a>
Since template parameters are passed and compiled during the pre-compilation phase, such untyped parameters are constants within the template code and cannot be modified
For this kind of parameter, C++ currently supports only integer typesint
(or may be converted toint
The type of thebool
), enumerations, pointers and reference types
C++11 supports assignment of untyped parameters at definition time, such astemplate<typename T, int b=100>
Template-defined parameters
Taking a class template as a class template parameter emphasizes the number of parameters of that class template, in addition to emphasizing that this type parameter must be a class template
// Class templates with a single template parameter
template<typename T>
struct S_Tmp{}.
// Class template with multiple template parameters
template<typename T, typename R>; // Multi-template parameter class template.
struct D_Tmp{}; // Class template with multiple template parameters.
// Class template with single parameter class template as argument
template<template<typename S> class T>
struct MyTest{}; // Class template with one-argument class template as parameter.
int main(){
MyTest<S_Tmp> tt1.
// MyTest<D_Tmp> tt1; // error
tt1; // error
}
Combination of template formal and real parameters
Implicit binding of function template real parameters
The compiler can derive the real parameters corresponding to the template's formal parameters based on the function's real parameter type, which allows you to omit the template parameter list when calling the function template.
Since the function call statement does not provide information about the type of the function's return value, the template's placeholder for the return value type must be the same as the placeholder for one of the formal parameters
pointer real parameter
In C++, a pointer is a datatype and thus can be used as a template real parameter
Use of the modifiers const and &
You can use modifiers in the list of template call parametersconst
cap (a poem)&
template<typename T1, typename T2>
const T1& add(const T1& a, const T2& b){
return a;
}
Template Specialization and Template Realization
Template specialization
Changes in data types are usually not related to business logic
If there are individual data types that have algorithms that differ from the algorithms for other types, these algorithms are written separately.
Specialization of function templates
If the function to determine the size of the numerical type and string type comparison algorithm is not the same, should be implemented separately
template<typename T>
T mymax(T a, T b){
return a>b?a:b;
}
template<>
char* mymax(char* a, char* b){
return (strcmp(a,b)<0)?b:a;
}
utilizationtemplate<>
It is for the purpose of incorporatingmaxt
Template system
Specialization and partial specialization of class templates
// Normal templates
template<typename T1, typename T2>
struct Test{};
// Specialized templates
template<typename T>
struct Test<int, T>{};
// Full specialization template
template<>
struct Test<int, float>{};
Representation of templates
Compiler priority in matching templates to generate entity code
- Specialization templates (functions or classes)
- Specialized templates (classes)
- Common templates (functions or classes)