为什么 std::queue 使用 std::vector 容器创建不会引发编译器错误

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

为什么 std::queue 使用 std::vector 容器创建不会引发编译器错误?

只有在调用pop时才会出现编译错误(这很清楚,因为vector没有提供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

因为class模板的成员函数在被调用之前不会被隐式实例化。

从 $14.7.1/2 隐式实例化 [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;

和/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
}

和/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.