当前位置:网站首页>Function templates and non template functions with the same name cannot be overloaded (definition of overloads)
Function templates and non template functions with the same name cannot be overloaded (definition of overloads)
2022-07-26 10:20:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
About the overloading mechanism of functions , It's a complicated problem , Among them, priority definition and best matching are involved , If you want to explain clearly , I'm afraid it's not clear in oneortwo articles . But if you master some commonly used “ law ”, It is also of great benefit to understand how the program selects overloaded functions , This article tries to put my understanding of knowledge , Combined with the following simple examples, briefly talk about the function overloading mechanism , The excerpt of the article lists some rules about how programs choose overloaded functions .: )
Examples are as follows :
#include <iostream>
//non-template function
inline const int& max( const int& a, const int& b )
{
std::cout << “non-template max() is called” << std::endl;
return a < b ? b : a;
}
//template function
template < typename T >
inline const T& max( const T& a, const T& b )
{
std::cout << “template max() is called” << std::endl;
return a < b ? b : a;
}
int main()
{
::max( 7.0, 42.0 ); //template max() is called
::max( ‘a’, ‘b’ ); //template max() is called
::max( 7, 42 ); //non-template max() is called
::max<>( 7, 42 ); //template max() is called
::max< double >( 7, 42 ); //template max() is called
::max( ‘a’, 42.7 ); //non-template max() is called
}
The program passed the compilation successfully , And run to get the result , explain Non function template functions and function templates with the same name can coexist . The program will select a function from the set of candidate overloaded functions to call through priority and best match ( See the following excerpt for the rules to be followed ).
The output of the program is shown in the comments of each function call , There must be no doubt about the first and second output results , What the program calls is the function template max, The following mainly analyzes the rest of the output .
【 One 】、max( 7, 42 ); Calling a non function template max(). When When other elements are equal , The overloading mechanism will preferentially call non function templates instead of function templates 【 For this question , Personally, I think it may be based on the following reasons : Reloading will reduce the efficiency of the program , This is true for non functional templates , This is especially true for more complex function templates ( At least one instantiation is required ), Therefore, the overloading mechanism will preferentially call non function templates instead of function templates .】. Those that cannot best match non functional templates , Then call the instantiated object of the function template , Such as the first and second function calls .
【 Two 】、max<>( 7, 42 ); Follow max( 7, 42 ); The only difference is that the former has an additional template parameter list , Remember the problem of function template parameters mentioned in the previous notes ?<> The parameters in are used to specify , The passed in parameter type and return value type , The order of parameters in the list corresponds to the order of types declared in the template . The parameter list here is empty , But it tells the compiler , This function only selects the best matching function call in the function template . alike ,max< double >( 7, 42 ); What is called is an instantiation object of the function template , The type of template parameter is specified here , So for the incoming value , The program will convert it ( from int To double), Then compare the sizes .
【 3、 ... and 】、 For the last function call max( ‘a’, 42.7 ); At first, I thought it was to call non functional templates , The result is indeed a call to a non functional template , My reason is that the types of the two parameters are obviously different , I see the explanation in the book later , That's what it says : Automatic type conversion , Only applicable to general functions ( That is, non function template ). In fact, there is no deviation in my understanding , Just not deep enough . If you feel ‘a'(char type ) Follow 42.7( The program defaults to double type ) Difference is too big , It's hard to understand the above sentence , Try this call max( ‘a’, 42 );( Generally, we will be right char and int Draw an implicit equal sign , Default char Namely int Subset , But in fact, it still needs an implicit transformation ) As a result, non function templates are called max().
//====================【 appendix : Some instructions about overloading 】====================
This part is mainly extracted from 《c++template》 Appendix to , There are a few changes in language organization . in addition ,《c++primer》 Overloading is also discussed in detail in .
【 One 】 When will it be overloaded ?
First , If it is called through function pointer or member function pointer , There will be no overload resolution , Because which function is called by the pointer at run time ( In fact, it points to the object ) To decide . secondly , Macros like functions cannot be overloaded , Therefore, overload resolution will not be performed .
【 Two 】 What kind of process is overloading ?
- Find name , Thus forming an initialized overloaded set ( close ).
- If necessary , Will use various methods to modify this set ( for example , When template deduction occurs ).
- Anything that does not match the call ( Even after considering implicit conversion and default arguments, they still don't match ) All candidate functions of are deleted from the overload set , The final set is : Feasible candidate function set .
- perform overloading resolution To find a best candidate function . If you can find , Then select the best candidate function ; otherwise , This call is ambiguous .
- Check the best candidate function selected . for example , If it has private members that cannot be accessed , Diagnostic information may be given .
【 3、 ... and 】 About the overload resolution mentioned above , According to what principle is the best candidate function selected ?
- Perfect match . Types and arguments of parameters ( expression ) Same type of , Or the type of the parameter is a reference to the actual parameter type ( You can also add const perhaps volatile qualifiers ).
- A slightly adjusted match . For example, the array is transformed into a pointer to the first element of the array , Or add const, So that the type is int** The argument matching type of is int const* const* Parameters of .
- The match of promotion occurs . Promotion is an implicit type conversion , It contains integer types with less space ( Such as bool,char,short Or some enumeration ) Convert to the type with more placeholders ( Such as int,unsigned int,long perhaps unsigned long), It also includes from float To double Type conversion of .
- Standard conversion occurs ( Type conversion ) The matching of . This includes any kind of standard transformation ( Such as int To float), But not Type conversion operators and single parameter constructors that do not contain implicit calls .
- Matching of user-defined transformation occurs . This allows any kind of implicit type conversion .
- Match with ellipsis . The ellipsis parameter can match any type ( But the match is not POD(plain old data) Types lead to undefined behavior )
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/128449.html Link to the original text :https://javaforall.cn
边栏推荐
- 畅听,网文流量竞争的下一站?
- The practice of OpenCV -- bank card number recognition
- Opencv image processing
- equals与==的区别
- The reason why go language is particularly slow to develop run and build commands
- 【Halcon视觉】软件编程思路
- Data communication foundation - layer 2 switching principle
- Use spiel expressions in custom annotations to dynamically obtain method parameters or execute methods
- 详细解析js中的混合方式构造对象(构造加属性,原型加方法)
- modelsim 安装教程(应用未安装)
猜你喜欢

3.1 leetcode daily question 6

Deduct daily question 838 of a certain day

数通基础-网络基础知识

Learning about opencv (4)

Transform between tree and array in JS (hide the children field if the child node of the tree is empty)

Basic usage of protobuf

【Halcon视觉】仿射变换

Li Kou daily question 917

Necessary for beginners: debug breakpoint debugging skills in idea and common breakpoint skills

Employee information management system based on Web
随机推荐
Draw arrows with openlayer
Reproduce the snake game in C language (I) build pages and construct snakes
【Halcon视觉】形态学腐蚀
INSTALL_ FAILED_ SHARED_ USER_ Incompatible error resolution
Under win10 64 bit, matlab fails to configure notebook
【Halcon视觉】形态学膨胀
Solution of inputting whole line string after inputting integer
MLX90640 红外热成像仪测温传感器模块开发笔记(六)
The problem of four columns of Hanoi Tower
简单化构造函数的继承方法(一)- 组合继承
Application of crosstab in SQL Server
数据库的复习--3.SQL语言
数据库的复习--1.概述
Meeting OA project (III) -- my meeting (meeting seating and submission for approval)
输入整数后输入整行字符串的解决方法
【Halcon视觉】算子的结构
数通基础-TCPIP参考模型
【杂谈】Error loading psycopg2 module :No module named psycopg2
string null转空字符串(空字符串是什么意思)
网易云UI模仿--&gt;侧边栏