当前位置:网站首页>Function template parameters (where are the function parameters)
Function template parameters (where are the function parameters)
2022-07-26 10:19:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
C++ Omission of template arguments
The template arguments cannot be omitted in the following cases : 1) There are contradictions in the information obtained from the template function argument table .
template<typename T> void fun(T const& a,T const& b); But when you call it, it is fun(250,250.4); Then you must write fun<int>(250,250.4); 2) You need to get a specific type of return value , Regardless of the type of parameter .
template<typename T,typename RT> RT fun(T const& a,T const& b); There is no way to deduce at this time , So you can rewrite template<typename RT,typename T> RT fun(T const& a,T const& b); Write as fun<double>(12,13); 3) The virtual type parameter does not appear in the formal parameter table of the template function .
use typename and class The parameters of the type declaration are called virtual type parameters , While using 《 Type modifiers 》 The declared parameters are called regular parameters 4) Function templates contain regular formal parameters .
template<typename T> void fun(); Directly when called fun()!!
Specifically template You can see the instructions online , Here I would like to emphasize a point about template A special case where the template argument is empty . Reprint the network about c++ Key points of grade examination . Knowledge point 4:
1.1 Function templates
1.1.1 Examination site 1: Concept and declaration of function templates
A function template is a model or template of a series of related functions , The source code form of these related functions is the same , Only the data types are different . For function templates , The data type itself becomes its parameter , Therefore, it is a parameterized function . Class member functions can also be declared as function templates . The format of declaring a function template is as follows : template < Template parameter table declaration > Return type Function name ( Function parameter table ) { …… // The body of the function }
among ,< Template parameter table declaration > By one or more “ Template parameters ” Composed of , If more than one , Separate them with commas .“ Template parameters ” Have the following 3 In the form of :
typename Parameter name class Parameter name Type modifiers Parameter name
The parameter name here can be any legal C++ identifier . The first two forms are equivalent , in other words , When declaring template parameters , keyword typename and class interchangeable . use typename or class The declared parameters are called virtual type parameters ; While using “ Type modifiers ” Declared parameters are called regular parameters . there “ Type modifiers ” Refers to specific data types ( Such as int、double、char etc. ). Function template < Template parameter table declaration > in , Be sure to include virtual type parameters , Conventional parameters can be selected according to actual needs .
< Template parameter table declaration > Virtual type parameters declared in can be used as :
Return value type of function Type of formal parameter of function The type of variable in the function body
example 1.1.1 The following is the beginning of the template declaration , The right one is ( ). A.template <T> B.template <class T1,T2> C.template <class T1,class T2> D.template <class T1;class T2> answer :C
example 1.1.2 The error in the following function template definition is ( ). A.template<class Q> B.template<class Q> Q F(Q x){return Q+x;} Q F(Q x){return x+x;} C.template<class T> D.template<class T> T F(T x){return x*x;} bool F(T x){return x>1;} analysis : Declared in each option Q and T Are virtual type parameters . Virtual type parameters declared in the function template formal parameter table can be used as : Return value type of function Type of formal parameter of function The type of variable in the function body Options B、C and D Conform to the above three usages . And the options A Let virtual type parameters Q It is wrong to directly participate in the operation . Virtual types are concrete types ( Such as int type ,double Type, etc. ) The abstraction of . We know ,int Itself cannot directly participate in mathematical operations , But defined by it int Type variable or int Type parameters can directly participate in the operation . Virtual type Q and T Nor can it directly participate in the operation , But defined by them “T type ” or “Q type ” Parameters of x Can participate in the operation . therefore , Options A in “Q+x” The expression of is wrong . answer :A 1.1.2 Examination site 2: template function
The functions declared in the function template are called template functions . The format of calling a template function is as follows : Function name < Template argument table > ( Function argument table ); or Function name ( Function argument table ); In the second format, all template arguments are omitted , Using this format requires certain conditions ( See the examination site for details 4). The member functions of class templates are all template functions .
example 1.1.3 The following function templates max The function is : Returns an array of a The value of the largest element in . Please complete the missing part at the horizontal line . template <typename T> T max (T a[], int n) { T m = a[0]; for (int i = 1; i < n; i++) if (a[i]>m) ; return m; } analysis : This question examines the definition of template function . When writing a function body , Template functions are the same as ordinary functions . According to the meaning , Back to m The value should be a The value of the largest element in , So when a[i]>m when , The larger a[i] Value is assigned to m. Traversing array a[] after , Final m Save the array a[] The value of the largest element in . 1.1.3 Examination site 3: Instantiation of function template
When calling template functions , The process that the compilation system generates a specific function definition according to the actual data type used is called the instantiation of function template . During instantiation , Use the actual type ( Such as int、long etc. ) Substitute virtual type . The process or result of instantiation is usually invisible , The compilation system will automatically pass the corresponding template arguments according to the specific conditions of function calls , Generate corresponding function instances . Each instance is a function definition . During instantiation , In addition to using various specific C++ Intrinsic data type replaces virtual type , You can also replace virtual types with some user-defined types , The custom types here include structures and some user-defined classes .
example 1.1.4 The output of the following program is . #include <iostream> using namespace std; template <typename T> T fun (T a, T b) {return (a<=b)?a:b;} int main() { cout<<fun(3,6)<<‘,'<<fun(3.14F,6.28F)<<endl; return 0; } analysis : This topic defines a template function fun, Its shape parameter a、b And function return types are T type . function fun The return function is a、b The smaller number in . stay main Function , First call fun when , It's actually called “int fun(int a,int b)” This function , Therefore, integer data is returned “3”. On the second call , In fact, it calls the function “float fun (float a, float b)”, Returns floating point data “3.14”. answer :3,3.14
1.1.4 Examination site 4: Omission of template arguments
When calling template functions , The compilation system needs enough information to identify the actual type corresponding to each virtual type parameter , Information can be obtained from two different sources : from “ Template argument table ”( stay “<” and “>” Between ) Or from the template “ Function argument table ”( stay “(” and “)” Between ),“ Template argument table ” Information of takes precedence over “ Function argument table ” Information about . If the information obtained from the latter can already determine the actual type corresponding to some or all of the virtual type parameters , And they happen to be “ Template parameter table declaration ” The last parameters in , It's in “ Template argument table ” These parameters can be omitted in . If all template arguments are omitted , Empty table “<>” You can omit it .
But in the following cases , Template arguments cannot be omitted .
① From template “ Function argument table ” There are contradictions in the information obtained in . for example , When the information obtained by the compilation system from a function argument is a virtual type parameter T( Assuming that T) The corresponding actual type is int, However, the information obtained from another function argument is the virtual type parameter T The corresponding actual type is double when , There is a contradiction .T It's impossible to be int and double type , This will cause the compiler to be unable to find the definition of the matching function template , Compile times error . One way to solve this problem is to show the virtual type parameters T Corresponding template arguments , mandatory T Corresponding to int or double. ② The virtual type parameter is used as the return value type of the function , And the function needs to return a specific type of value , Regardless of the type of function arguments . under these circumstances , You need to use template arguments to force virtual type parameters to correspond to specific types . ③ The virtual type parameter does not appear in the template “ Function parameter table ” in . At this time, you can't get from the “ Function argument table ” Get the corresponding information , Therefore, template arguments cannot be omitted . ④ Function templates contain regular formal parameters . General parameters are specific type modifiers ( Such as int、double、char* etc. ) Defined , The corresponding argument must be a constant expression . therefore , The information of general parameters cannot be obtained from the “ Function argument table ” gain , When calling a template function, the template arguments corresponding to the general parameters must be displayed .
example 1.1.5 There are the following function template definitions : template <class T> T func (T x, T y){ return x*x+y*y;} In the following pairs func In call to , The wrong is ( ). A.func(3,5); B.func(3.0,5.5); C.func(3,5.5); D.func<int>(3,5.5); analysis : For the template function defined in this question , If you use the option C in “func(3,5.5);” To call , At compile time “template parameter ‘T’ is ambiguous,could be ‘double’ or ‘int’ ” Error of , in other words T The corresponding actual type is ambiguous . Compile the system from the first parameter “3” The information obtained is “T Corresponding to int”, And from the second parameter “5.5” The information obtained at is “T Corresponding to double”, The two contradict each other , Therefore, an error occurs during compilation . Options D Template arguments are provided in <int>, Because template arguments take precedence over function arguments , therefore T The corresponding actual type is clear , Here it is int type . During the call ,double The parameters of type “5.5” Will be automatically converted to int type . The selection A and B The types of the arguments of the two functions provided are consistent , There is no contradiction . answer :C
example 1.1.6 There are the following function template declarations : template <typename T> T Max(T a,T b) {return (a>=b)?a:b;} The following pairs of function templates Max The error in the call of is ( ). A.Max(3.5,4.5) B.Max(3.5,4) C.Max<double>(3.5,4.5) D.Max<double>(3.5,4) answer :B
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/129465.html Link to the original text :https://javaforall.cn
边栏推荐
- Wu Enda linear regression of machine learning
- Flask框架初学-04-flask蓝图及代码抽离
- Redis realizes distributed lock and gets a watchdog
- Dynamically determine file types through links
- Rowselection emptying in a-table
- Replay the snake game with C language (II) end
- 简单化构造函数的继承方法(一)- 组合继承
- C language course design Tetris (Part 2)
- 在.NET 6.0中配置WebHostBuilder
- 数通基础-STP原理
猜你喜欢
Learning about opencv (2)
Error in render: "typeerror: cannot read properties of undefined (reading 'length')" --- error when calling interface
Li Kou daily question 917
On the compilation of student management system of C language course (simple version)
[Qualcomm][Network] qti服务分析
Learning about tensor (III)
Vs Code configures go locale and successfully installs go related plug-ins in vscode problem: Tools failed to install
Session based recommendations with recurrent neural networks
Data communication foundation telnet remote management equipment
【有奖提问】向图灵奖得主、贝叶斯网络之父 Judea Pearl 提问啦
随机推荐
Interview shock 68: why does TCP need three handshakes?
Data communication foundation STP principle
【有奖提问】向图灵奖得主、贝叶斯网络之父 Judea Pearl 提问啦
【Halcon视觉】软件编程思路
Learning about opencv (1)
The practice of OpenCV -- bank card number recognition
Okaleido生态核心权益OKA,尽在聚变Mining模式
【Halcon视觉】图像滤波
【Halcon视觉】极坐标变换
【C#语言】具名类型和匿名类型
Cause: could't make a guess for solution
How to use Gmail to pick up / send mail on Foxmail
All codes of Tetris
Study notes of the fifth week of sophomore year
面试第一家公司的面试题及答案(一)
Transform between tree and array in JS (hide the children field if the child node of the tree is empty)
Learning about tensor (III)
万字详解“用知识图谱驱动企业业绩增长”
Prevent XSS attacks
【Halcon视觉】图像灰度变化