티스토리 뷰



Templates in C++ 


Templates in C++ are a function or a class to implement with multiple data types using templates. Templates are the basic part of the *generic programming. The template has two different types, Function template and Class template. 


Generic programming

Generic programming is a programming method that can increase the reusability by focusing on a way in which one value can have multiple data types, regardless of the data type.




Example of a Function template I

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template<typename T> // Template definition
T sum(T a,T b){
    return a + b;
}
 
int main() {
    int a = 0, b = 0;
    cout << "Enter the first number: ";
    cin >> a;
 
    cout << "Enter the sencond number: ";
    cin >> b;
 
    cout << "sum " << sum(a , b) << endl;
 
    return 0;
}
cs



Result





Example of a Function template II

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template<typename t, typename t1>
 
t sum(t a, t1 b) {
    
    return a + b;
}
 
int main()
{
    cout << sum(2.53<< endl//5.5
    cout << sum(4.12<< endl//6.1
 
    return 0;
}
cs








Class Templates

In order to create an object, memory must be allocated before the constructor is called. If the data type of the arguments missed, OS doesn't know how much memory to allocate. For that reason, although declaring a class template is no difference from declaring a function template, you must specify the type when you use the class template.




Example of a Class template


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
template<typename T>
class Person {
private:
    T data;
public:
    Person(T data);
    void setInfo(T data);
    T getInfo();
};
 
template <typename T>
Person<T>::Person(T data) {
    this->data = data;
}
 
template <typename T>
void Person<T>::setInfo(T data){
    this->data = data;
}
 
template <typename T>
T Person<T>::getInfo(){
    return data;
}
 
int main(void) {
    Person<int> p1(30);
    p1.setInfo(20);
 
    Person<string> p2("lol");
    
    cout << p1.getInfo() << endl//20
    cout << p2.getInfo() << endl//lol
}
cs


'C++' 카테고리의 다른 글

Virtual Function in C++  (0) 2018.11.22
Friend in C++  (0) 2018.11.22
Exception handling (Try Throw and Catch) in C++  (0) 2018.11.09
Inline function in C++  (0) 2018.11.09
Copy constructor(Deep copy, Shallow copy) in C++  (0) 2018.11.09