I would describe about using templates in c++.
- functions using templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters#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; }
- classes using templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters#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; }
- 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters#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