当前位置:网站首页>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 
边栏推荐
- 由两个栈组成的队列
- Component splitting practice
- Uncertainty principle
- Pychart shares third-party modules among different projects
- GCD maximum common divisor
- English grammar_ Adjective / adverb Level 3 - Comparative_ Useful Expressions
- Analysis of future teacher research ability under steam education framework
- Pinda general permission system (day 5~day 6)
- Particle theory of light (photoelectric effect / Compton effect)
- In the era of video explosion, who is supporting the high-speed operation of video ecological network?
猜你喜欢

Web APIs DOM event foundation dark horse programmer

Introduction notes to machine learning

Understanding and learning of parental delegation mechanism

ambari SSLError: Failed to connect. Please check openssl library versions.

MSc 307 (88) (2010 FTPC code) Part 2 smoke and toxicity test

Are the two flame retardant standards of European furniture en 597-1 and en 597-2 the same?

Visualization of loss using tensorboard

设计一个有getMin功能的栈

Market competitiveness of robot programming education

From zero to one, I will teach you to build a "search by text and map" search service (I)
随机推荐
ERP升级的另一种选择,MES系统
Analysis of future teacher research ability under steam education framework
04 MongoDB各种查询操作 以及聚合操作总结
由两个栈组成的队列
基于正点原子stm32的mini板的TFTLCD显示实验
Arrangement of basic electrical knowledge (I)
光伏板怎么申请ASTM E108阻燃测试?
Introduction to multi project development, basic design class library project use
English语法_形容词/副词3级 - 比较级
美创数据安全管理平台获信通院“数据安全产品能力验证计划”评测证书
月赛补题
After launching the MES system, these changes have taken place in the enterprise
软件测试报告怎么编写?第三方性能报告范文模板来了
抖音实战~取关博主
美创入选“2022 CCIA中国网络安全竞争力50强”榜单
MSC 307(88) (2010 FTPC Code)第2部分烟气和毒性测试
品达通用权限系统(Day 5~Day 6)
Particle theory of light (photoelectric effect / Compton effect)
sqlserver 数据库之事物使用入门 案例
Using elk to build a log analysis system (I) -- component introduction