Sunday, 22 September 2013

Using Templates in C++ Programming

I would describe about using templates in c++.

  1. functions using templates  
    #include <bits/stdc++.h>
    using namespace std;
    template <class T>
    T Max (T a, T b)
    {
    T res = a > b ? a : b;
    return res;
    }
    int main()
    {
    cout << Max <int> (3, 4) << endl; // 4
    cout << Max <double> (3.5, 4.6) << endl; // 4.6
    cout << Max <string> ("abc", "bcd") << endl; // bcd
    return 0;
    }

  2. classes using templates  
    #include <bits/stdc++.h>
    using namespace std;
    template <class T>
    class point
    {
    public :
    T x, y;
    point ()
    {
    }
    point (T _x, T _y)
    {
    x = _x;
    y = _y;
    }
    T dist ()
    {
    return x * x + y * y;
    }
    };
    int main()
    {
    point <int> p (3, 4);
    cout << p.dist() << endl; // 25
    point <double> q (3.5, 4.5);
    cout << q.dist() << endl; // 32.5
    return 0;
    }

  3. Template Specialization  
    Template Specialization means that specialize your template for some particular type. eg. you define add function for integers to be integers addition but for strings it may be addition. So You need to define it seperately.
    #include <bits/stdc++.h>
    using namespace std;
    template <class T>
    class SquareIt
    {
    public:
    T x;
    SquareIt ()
    {
    }
    SquareIt (T _x)
    {
    x = _x;
    }
    T getResult ()
    {
    return x * x;
    }
    };
    template <>
    class SquareIt <string>
    {
    public:
    string x;
    SquareIt ()
    {
    }
    SquareIt (string _x)
    {
    x = _x;
    }
    string getResult ()
    {
    return x + x;
    }
    };
    int main()
    {
    SquareIt <int> sq1 (5);
    cout << sq1.getResult() << endl;
    SquareIt <string> sq2 ("abc");
    cout << sq2.getResult() << endl;
    return 0;
    }

No comments:

Post a Comment