911
911

Reputation: 928

Why std::queue creation with std::vector container does not raise compiler error

Why std::queue creation with std::vector container does not raise compiler error?

Compiler error occurs only when pop is called (this is clear as vector does not provide pop_front()).

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

int main()
{
    queue<int, vector<int>> s;

    s.push(10);

    cout << s.front() << endl;

    s.pop();

    return 0;
}

DEMO

Upvotes: 4

Views: 808

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

Because the member function of a class template will not be implicit instantiated until it being called.

From $14.7.1/2 Implicit instantiation [temp.inst]:

Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist;

And /4:

[ Example:
template<class T> struct Z {
void f();
void g();
};
void h() {
Z<int> a; // instantiation of class Z<int> required
Z<char>* p; // instantiation of class Z<char> not required
Z<double>* q; // instantiation of class Z<double> not required
a.f(); // instantiation of Z<int>::f() required
p->g(); // instantiation of class Z<char> required, and
// instantiation of Z<char>::g() required
}

And /11:

An implementation shall not implicitly instantiate a function template, a variable template, a member template, a non-virtual member function, a member class, or a static data member of a class template that does not require instantiation.

Upvotes: 5

Related Questions