2. Function Overload
2
void printData(int value) {
cout<<"The value is "<<value<<endl;
}
Bagaimana untuk mencetak tipe string? int?
Overload: Buat beberapa fungsi dengan signature
berbeda
void printData(string value) {
cout<<"The value is "<<value<<endl;
}
STL – IKP213
3. Template
3
template<typename T>
void printData(T value) {
cout<<"The value is "<<value<<endl;
}
Mendefinisikan T sebagai sebuah tipe template
T akan diinstantiasi sesuai kebutuhan
double d = 10.01;
string s = "Template";
printData(d);
printData(s);
STL – IKP213
4. Template Parameter
4
Sintaks penulisan
template<typename name>
template<class name>
Pemanggilan fungsi / class akan diinstantiasi sesuai tipe
yang digunakan
template<typename T>
void func(T value) {
const T& ref=value;
T* p=new T;
T temp(23);
}
STL – IKP213
5. Template Parameter
5
Jika ada definisi func<int>, akan digenerate
sebuah instantiasi fungsi
void func(int value) {
const int& ref=value;
int* p=new int;
int temp(23);
}
Semua kemunculan T digantikan int
STL – IKP213
6. Template Parameter
6
Jika ada definisi func<string>, akan muncul
kesalahan kompilasi
void func(string value) {
const string& ref=value;
string* p=new string;
string temp(23);
}
Karena string temp(23) tidak valid
STL – IKP213
7. Standard Template Library (STL)
7
Koleksi containers dan algorithms
Containers
Class untuk menampung sekumpulan objek
vector, list, queue, deque, priority_queue, stack, map,
multimap, set, multiset
STL – IKP213
12. Matriks
12
// Vector length of 3 initialized to 0
vector<int> vI1Matrix(3,0);
// Vector length of 4 initialized to hold another
// vector vI1Matrix which has been initialized
// to 0
vector< vector<int> > vI2Matrix(4, vI1Matrix);
// Vector of length 5 containing two dimensional
// vectors
vector< vector< vector<int> > > vI3Matrix(5,
vI2Matrix);
STL – IKP213
13. Dalam satu baris
13
vector< vector< vector<int> > > vI3Matrix(2,
vector< vector<int> > (3, vector<int>(4,0)) );
STL – IKP213