Difference between Preprocessor Directives and Function Templates in C++In this article, we will discuss about the preprocessor directives and function template in C++. But before discussing their differences, we must know about the preprocessor directives and function template. What are Preprocessor Directives?Preprocessor programs give preprocessor directives that instruct the compiler to process the source code without compiling it. All of these directives from the preprocessor begin with a '#' (hash) symbol. The '#' sign indicates that the preprocessing program will process any statement that begins with a '#'. These preprocessing directives can be used anywhere in our software. Some preprocessing directives are #include, #define, #ifndef, etc. The '#' symbol provides a route to the preprocessor and a command like include is handled by the preprocessor program. For example, the #include is going to include the code or contents of the specified file in the application. Example:Let us take an example to illustrate the use of preprocessor directives in C++. Output: The Min value is: 89 What are Function Templates?In C++, a template is a very powerful tool. The simple idea is to give the data type as a parameter to avoid writing the same code for several data types. For example, the function sort() may be required for several data types by a software firm. We can construct a single sort() function and send the datatype as an argument instead of creating and maintaining numerous scripts. Example:Let us take an example to illustrate the use of function templates in C++. Output: The Minimum value of both is: 56 Using the function template, we can create generic functions that may operate on any data. For instance, the function template that determines the minimum of two values of any kind may be defined as follows: However, preprocessor directives made using preprocessor directive #define can also be used to do this work. Thus, we can define the minimum of the two integers as follows: Most of us prefer to utilize templates in C++ instead of pre-processor directives because:
Key Differences between the Preprocessor directives and Function templates:There are several differences between Preprocessor directives and function templates. Some main differences between Preprocessor directives and function templates are as follows:
Next TopicFord Fulkerson Algorithm in C++
|