Templates are used for generic programming. - C++ basic concepts

Q.  _________________are used for generic programming.
- Published on 19 Oct 15

a. Inheritance
b. Virtual Functions
c. Templates
d. None of these

ANSWER: Templates
 

    Discussion

  • Nihal   -Posted on 08 Oct 15
    Templates are used for generic programming. Using templates, you can create generic functions and classes. By using this technique you can define a general set of operations that will be applied to various types of data. A generic function is created using the keyword template
    template
    void swapargs(T &a, T &b)
    {
    T temp;
    temp = a;
    a = b;
    b = temp;
    }
    int main()
    {
    int i=10, j=20;
    double x=5.10, y=3.30;
    char a='x', b='z';

    swapargs(i, j); // swap integers
    swapargs(x, y); // swap floats
    swapargs(a, b); // swap chars
    cout << "Swapped i, j: " << i <<" " << j << '\n';
    cout << "Swapped x, y: " << x << " " << y << '\n';
    cout << "Swapped a, b: " << a << " " << b << '\n';
    return 0;
    }
    Output:
    Swapped i, j: 20 10
    Swapped x, y: 3.3 5.1
    Swapped a, b: z x

Post your comment / Share knowledge


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)