📜  C++中的预处理程序指令和函数模板之间的区别

📅  最后修改于: 2021-05-30 17:10:15             🧑  作者: Mango

预处理程序指令是在编译之前处理我们的源代码的程序。在C / C++中编写程序和执行程序之间涉及许多步骤。

下面是说明函数模板功能的程序:

C++
// C++ program to illustrate
// preprocessor directives
#include 
  
#define min(a, b) ((a < b) ? a : b)
  
using namespace std;
  
// Driver code
int main()
{
    int a = 2, b = 4;
  
    // Find the minimum of a and b
    cout << "Minimum of both is: "
         << min(a, b);
  
    return 0;
}


C++
// C++ program to illustrate the use
// of Function Templates
#include 
#include 
using namespace std;
  
// Function Template
template 
T Min(T x, T y)
{
    return (x < y) ? x : y;
}
  
// Driver Code
int main()
{
    int a = 4, b = 8;
  
    // Find the minimum of a and b
    cout << "Minimum of both is: " << min(a, b);
  
    return 0;
}


输出:
Minimum of both is: 2

函数模板是通用函数,可以处理不同的数据类型,而无需任何单独的代码。

下面是说明函数模板功能的程序:

C++

// C++ program to illustrate the use
// of Function Templates
#include 
#include 
using namespace std;
  
// Function Template
template 
T Min(T x, T y)
{
    return (x < y) ? x : y;
}
  
// Driver Code
int main()
{
    int a = 4, b = 8;
  
    // Find the minimum of a and b
    cout << "Minimum of both is: " << min(a, b);
  
    return 0;
}
输出:
Minimum of both is: 4

函数模板用于制作可与任何数据类型一起使用的通用功能。例如,用于计算任何类型的至少2个值的函数模板可以定义为:

template 
T minimum(T a, T b)
{
   return (a < b) ? a : b;
}

但是,也可以使用预先创建的处理器指令使用预处理指令的#define执行此任务。因此,两个数字中的最小值可定义为:

#define minimum(a, b) ((a < b) ? a : b)

预处理程序指令也可以通过使用以下语句来实现:

minimum(30, 35);
minimum(30.5, 40.5);

在C++中,我们大多数人都喜欢使用模板而不是预处理器指令,因为:

  • 对于预处理器指令,不进行类型检查。但是对于模板,完全类型检查由编译器完成。
  • 预处理程序指令可能会调用意外结果。考虑一个宏,该宏可将任何数字的平方计算为:
#define sqr(x) (x*x)
  • 现在,如果使用以下语句调用此宏,则x = sqr(4 + 4);则预期输出为64,但会生成24,因为宏主体中的任何x都被4 + 4替换,从而导致x = 4 + 4 * 4 + 4 = 24,但是在模板的情况下,不会获得此类意外结果。

以下是两者之间的表格差异:

S. No. Pre-processor directives Function Templates
1 There is no type checking There is full type checking
2 They are preprocessed They are compiled
3 They can work with any data type They are used with #define preprocessor directives
4 They can cause an unexpected result No such unexpected results are obtained.
5 They don’t ensure type safety in instance They do ensure type safety
6 They have explicit full specialization They don’t have explicit full specialization
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”