Some advance knowledge in C/C++ _ Part 1

In this series, I will remind some advance knowledge in C/C++, included:
1. Function template
2. Class template
3. Function pointer and array of function pointer
4. Combination of function template and function pointer

In the first post, let’s consider Function template
;
I. Introduce
We will use base function is to swap two value:

#include
#include
using namespace std;
void Swap(int &x, int &y)
{
    int temp = x;
    x = y;
    y = temp;
}
void main()
{
    int x = 1, y = 2;
    Swap(x, y);
    cout<<"x = "<<x<<", y = "<<y;
    getch();
}

This program is correct for two value with “int” datatype. But, if we want to swap two float value, how do we do? Rewrite swap function for float value? It seems to be good if we have only int and float datatype. Suppose the program want to swap 10 different datatypes …?

C++ have a solution in this situation by using Function Template. In other words, we use a general datatype which represented for all datatypes.

II. HOW TO DO
Let’s the swap function below:

template class
Swap(T &x, T &y)
{
    T temp = x;
    x = y; y = temp;
}

We need to declare template for the function with: template class
After that, we use T as a datatype. Depend on datatype which is passed to function, T is that datatype.
For example:
1.

void main()
{
    int x = 1, y = 2;
    Swap(x, y);
cout<<"x = "<<x<<", y = "< T is int datatype

2.

void main()
{
    float x = 1, y = 2;
    Swap(x, y);
    cout<<"x = "<<x<<", y = "< T is float datatype

III. Note
We should only use Function template with input/output method of C++
The reason for this is that C++ doesn’t care specifically datatype.
For example, the below program use input/output method of C library. This will generate an error.

#include
#include
template
void Sum(T x, T y)
{
    printf("x + y = %d", x + y); // ? Why is %d when T is unkown.
}
void main()
{
    double x = 1, y = 2;
    Sum(x,y); // x + y = 0 . Unexpect result
    getch();
}

If we use input/output method of C++ library, the program is ok.

#include
#include
using namespace std;
template
void Sum(T x, T y)
{
    cout<<"x + y = "<<x+y; // OK
}
void main()
{
    double x = 1, y = 2;
    Sum(x,y); // x + y = 3
    getch();
}

Let’s finish the first post at here. In the next post, we will discuss Class template.