📜  C ++中的重载函数模板

📅  最后修改于: 2021-05-31 19:02:15             🧑  作者: Mango

模板:

  • 模板是一种工具,它可以减少编写与在那些地方可以使用的模板相同的代码的工作。
  • 模板函数可以通过一个非模板函数被重载或使用普通的函数模板。

函数重载在函数重载中,函数可能具有相同的定义,但参数不同。下面是C++程序,用于说明函数重载:

C++
// C++ program to demonstrate the
// function overloading
#include 
using namespace std;
  
// Function to calculate square
void square(int a)
{
    cout << "Square of " << a
         << " is " << a * a
         << endl;
}
  
// Function to calculate square
void square(double a)
{
    cout << "Square of " << a
         << " is " << a * a
         << endl;
}
  
// Driver Code
int main()
{
    // Function Call for side as
    // 9 i.e., integer
    square(9);
  
    // Function Call for side as
    // 2.25 i.e., double
    square(2.25);
    return 0;
}


C++
// C++ program to illustrate overloading
// of template function using an
// explicit function
#include 
using namespace std;
  
// Template declaration
template 
  
// Template overloading of function
void display(T t1)
{
    cout << "Displaying Template: "
         << t1 << "\n";
}
  
// Template overloading of function
void display(int t1)
{
    cout << "Explicitly display: "
         << t1 << "\n";
}
  
// Driver Code
int main()
{
    // Function Call with a
    // different arguments
    display(200);
    display(12.40);
    display('G');
  
    return 0;
}


输出:
Square of 9 is 81
Square of 2.25 is 5.0625

解释:

  • 在上面的代码中,正方形被重载了不同的参数。
  • 函数square也可以重载其他参数,每次其他参数都需要相同的名称和不同的参数。
  • 为了减少这些工作,C++引入了一种称为函数模板的泛型类型。

函数模板函数模板与常规函数具有相同的语法,但是它以关键字模板开头,后跟括在尖括号<>中的模板参数

模板函数重载:

  • 函数模板的名称相同,但是用不同的参数调用称为函数模板重载
  • 如果函数模板与普通模板相同,则函数名称保持不变,但参数数量不同。
  • 当函数模板被非模板函数重载时,函数名称保持不变,但函数的自变量不同。

以下是使用显式函数说明模板函数重载的程序:

C++

// C++ program to illustrate overloading
// of template function using an
// explicit function
#include 
using namespace std;
  
// Template declaration
template 
  
// Template overloading of function
void display(T t1)
{
    cout << "Displaying Template: "
         << t1 << "\n";
}
  
// Template overloading of function
void display(int t1)
{
    cout << "Explicitly display: "
         << t1 << "\n";
}
  
// Driver Code
int main()
{
    // Function Call with a
    // different arguments
    display(200);
    display(12.40);
    display('G');
  
    return 0;
}
输出:
Explicitly display: 200
Displaying Template: 12.4
Displaying Template: G
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”