0

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(); ?

  • 5
    Possible duplicate of [Where and why do I have to put the "template" and "typename" keywords?](https://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords) –  Jun 19 '17 at 04:20
  • 1
    The title is misleading. The actual question is not about `initializer_list`. –  Jun 19 '17 at 04:23

0 Answers0