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

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

本文关键字:std 编译 错误 创建 vector 为什么 queue      更新时间:2023-10-16

为什么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;
}
演示

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

From $14.7.1/2隐式实例化[temp.inst]:

除非类模板或成员模板的成员已经显式实例化或显式特化,即专门化的属性,在特化时隐式实例化成员在要求成员定义存在的上下文中引用;

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

实现不能隐式实例化函数模板、变量模板、成员模板、非虚成员函数、成员类或类模板的静态数据成员不需要实例化。