Class templates
I have a question, I'm learning templates with classes, when I founded how vector from STL uses an object called initializer_list.
So I tried to make my first try with two objects.
#include <iostream>
#include <vector>
#include <initializer_list>
using namespace std;
class A {
private:
int *a;
int size;
public:
A(initializer_list<int> list) {
size = list.size();
a = new int[size];
// Note here how I create an iterator for initializer_list
initializer_list<int>::iterator it = list.begin();
for (int i = 0; it != list.end(); ++it, ++i)
a[i] = *it;
}
};
template <class T>
class B {
private:
T *b;
int size;
public:
B(initializer_list<T> list) {
size = list.size();
b = new T[size];
// My question relies here
// If I declare my iterator like I did above it will not compile
// initializer_list<T>::iterator it = list.begin(); will fail
typename initializer_list<T>::iterator it = list.begin(); // This will work
// class initializer_list<T>::iterator it = list.begin(); will work too
for (int i = 0; it != list.end(); ++it, ++i)
a[i] = *it;
}
};
So why in my class B
I have to type typename/class
before initializer_list::iterator it = list.begin();
?