当前位置:网站首页>Little knowledge about function templates --
Little knowledge about function templates --
2022-06-28 04:12:00 【All fall】
This article introduces the concept of function template 、 Usage and how to create function templates and how to use function templates ......
The general form of a function template definition is as follows :
template< Type formal parameter table >
Return type Function name ( Form parameter table )
{
... // The body of the function
}
The methods we know before to exchange two variables are Macro definition 、 function , Both of these methods can realize the exchange of two variables , But each has its own advantages and disadvantages
Macro definition :
- advantage :
Code reuse , Suitable for all types
- shortcoming :
Missing type check , Macros are replaced in the preprocessing phase , The compiler does not know the existence of macros
function :
- advantage :
Real function calls , The compiler checks the type
- shortcoming :
Functions need to be defined repeatedly for different types , Code can't be reused
Both of the above methods have their own advantages and disadvantages , But in C++ in , There is Generic Programming The concept of : namely Programming without considering specific data types The way ( as follows )
For a series of functions with the same function body, the same number of parameters and different parameter types , Can be replaced by function templates , You only need to define the function template once .
Function template passed template And typename(class Instead of The effect is consistent ) Two keywords to define , as follows

The above defines a function template for variable exchange , There are two ways to use function templates
- Automatic type push to call Swap(a, b)
- The specific type shows the call Swap<int>(a, b)
template<typename t>
t max(t a, t b)
{
return a > b ? a : b;
}
int main()
{
int a = 0;
// There is only one data type in the template parameter list , The only arguments passed in are ⼀ Type of data
// Template functions can be generated directly from function templates
// Implicitly instantiate
a = max(1, 2);
// There are only... In the template parameter list ⼀ Type of data , But the arguments passed in at this time have two data types
// You need to force a type conversion when calling , Ensure that the number of types of the argument and the number of types of the template parameter list ⼀ Cause
// When generating template functions from function templates, the compiler cannot perform automatic implicit conversion , Cast to display
a = max(1, (int)2.0);
a = max((double)1, 2.0);
// Explicit conversions can also be converted in the form of angle brackets
// Explicitly instantiate
a = max<int>(1, 2.0);
a = max<double>(1, 2.0);
return 0;
}It should be noted that : Function templates Implicit type conversion is not supported
There's another way : To specify explicitly
The explicit materialization of function templates is the redefinition of function templates , The specific format is as follows :
template< > Function return value type Function name < Instantiation type >( parameter list )
{
// The body of the function is redefined
}
Explicitly instantiate You only need to explicitly declare the type of the template parameter There is no need to redefine the implementation of the function template , And explicit concretization The implementation of the function template needs to be redefined .
// Define a function template for exchanging two data , Examples are as follows
template<typename T>
void swap(T& t1, T& t2)
{
T temp = t1;
t1 = t2;
t2 = temp;
}
// But now there are the following structure definitions
struct Student
{
int id;
char name[20];
float score;
};
// Now we just want to exchange two students' id, Then we can solve this problem with explicit materialization
template<> void swap<Student>(Student& s1, Student& s2)
{
int temp = s1.id;
s1.id = s2.id;
s2.id = temp;
}If the function has multiple prototypes , When the compiler selects a function call , Non template functions take precedence over template functions , Explicit concrete templates take precedence over function templates , For example, the following three definitions :
void swap(int&, int&); // Direct definition
template<typename T>void swap(T& t1, T& t2); // Template definition
template<> void swap<int>(int&, int&); // To specify explicitly How to understand that ?
int a, int b There is swap(a, b) call , Directly defined functions will be called first ; without , Call Explicit materialization ; Neither of them exists , Only then do you call the template function .
Function templates can also be overloaded , Similar to function overloading , I won't go into details here .
When using a function template, you need Be careful The problem of :
1) < > Each type parameter in the must be used at least once in the function template parameter list .
for example , The following function template declaration is incorrect .
template<typename T1, typename T2>
void func(T1 t)
{
}The function template declares two parameters T1 And T2, But in use only T1, Not used T2.
2) An object with the same name as a template parameter declared in the global scope 、 Function or type , It will be hidden in the function template .
for example :
int num;
template<typename T>
void func(T t)
{
T num;
cout << num << endl; // The output is a local variable num, overall situation int Type of num blocked
}Accessed in the body of a function num yes T Variable of type num, Not the whole situation int Variable of type num.( Local priority )
3) An object or type declared in a function template cannot have the same name as a template parameter .
for example :
template<typename T>
void func(T t)
{
typedef float T; // error , The defined type is the same as the template parameter name
}4) Template parameter names can only be used once in the same template parameter list , However, it can be reused between multiple function template declarations or definitions .
for example :
template<typename T, typename T> // error , Define template parameters repeatedly in the same template
void func1(T t1, T t2)
{}
template<typename T>
void func2(T t1)
{}
template<typename T> // The same template parameter name can be used repeatedly in different function templates
void func3(T t1)
{}5) The template parameter names used by the template definition and multiple declarations do not have to be the same .
for example :
// Forward declaration of template
template<typename T>
void func1(T t1, T t2);
// Definition of template
template<typename U>
void func1(U t1, U t2)
{
}6) If the function template has multiple template parameters , The keyword must be used before each template parameter class or typename modification .
for example :
template<typename T, typename U> // The two keywords can be mixed
void func(T t, U u)
{}
template<typename T, U> // error , Every template parameter must be preceded by a keyword
void func(T t, U u)
{}That's the end of this article .
If it works , Please give me a favor !
Thank you guys 
边栏推荐
- Does the applet image component not display pictures?
- A preliminary study of blackbody radiation
- English grammar_ Adjective / adverb Level 3 - Comparative
- How to apply for ASTM E108 flame retardant test for photovoltaic panels?
- RT-Thread 双向链表(学习笔记)
- Zipkin service link tracking
- 第一个.net core MVC项目
- 基于arm5718的Shell脚本参数传递的2种方法
- @Transactional失效的几种场景
- English notes - cause and effect
猜你喜欢

English grammar_ Adjective / adverb Level 3 - Comparative_ Useful Expressions

GenICam GenTL 标准 ver1.5(2)

Understanding and learning of parental delegation mechanism

关于 SY8120I 的DC-DC的降压芯片的学习(12V降至3.3V)

leetcode - 329. 矩阵中的最长递增路径

机器学习入门笔记

猫狗队列的问题

In the era of video explosion, who is supporting the high-speed operation of video ecological network?

Secouer le son et se battre ~ prêter attention au blogueur

Does the applet image component not display pictures?
随机推荐
Uncertainty principle
Open the field of maker education and creation
English grammar_ Adjective / adverb Level 3 - Comparative_ Useful Expressions
欧洲家具EN 597-1 跟EN 597-2两个阻燃标准一样吗?
设计一个有getMin功能的栈
月赛补题
Reading notes of top performance version 2 (II) -- CPU monitoring
02 MongoDB数据类型、重要概念以及shell常用指令
How to apply for ASTM E108 flame retardant test for photovoltaic panels?
English语法_形容词/副词3级-比较级_常用短语
Building a server monitoring platform with telegraf influxdb grafana
How the uni app automatically switches the requested address according to the environment
抖音实战~取关博主
【Linux】【Mysql】ERROR 1698 (28000): Access denied for user ‘root‘@‘localhost‘
leetcode - 329. 矩阵中的最长递增路径
Uncover the mystery of SSL and learn how to protect data with SSL
ERP升级的另一种选择,MES系统
Chapter 14 AC-DC power supply front stage circuit note I
单一职责原则
ELK 搭建日志分析系统 + Zipkin服务链路追踪整合