标准::向量声明中使用的模板参数

Template parameters used in std::vector declaration

本文关键字:参数 向量 声明 标准      更新时间:2023-10-16

我正在从这里阅读有关std::vector类的信息。 我对使用的模板参数有点困惑。使用的声明是:

template<
class T
class Allocator = std::allocator<T> 
> class vector; 

参数class Allocator = std::allocator<T>让我感到困惑。

这是模板模板参数的示例吗?

但是,我认为它可能适合我在这里找到的Type template parametertype-parameter-key name(optional) = default

我尝试了以下实验,但它给出了编译错误:

d1 的值在常量表达式中不可用

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
//Type template parameter
template<class T>
class foo{
T a;
public : 
void sayHello(){
cout<<"Say Hello to  : "<<a<<endl; //Would have taken care of the overloaading << , if there were no other errors
}
void  setVal(T temp){
this->a = temp;
}
};
class dog{
string name ="labrador";
};
int main(){
dog d1;
//foo<d1> foo_1; ////Does not work
return 0;
} 

如何使上述代码工作?

http://www.cplusplus.com/doc/oldtutorial/templates/简单的语法错误伙伴,传递类型名称,而不是类型实例标识符。 为了使它编译,我做了一个快速实现的 ostream 重载。

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
//Type template parameter
template<class T>
class foo{
T a;
public :
void sayHello(){
cout<<"Say Hello to  : "<<a<<endl; //Would have taken care of the overloaading << , if there were no other errors
}
void  setVal(T temp){
this->a = temp;
}
};
class dog{
string name ="labrador";
friend ostream& operator<<(ostream& os, const dog& dt);
};
ostream& operator<<(ostream& os, const dog& dt)
{
os << "dog stuff" << endl;
return os;
}
int main(){
dog d1;
foo<dog> foo_1; ////Does not work
foo_1.sayHello();
return 0;
}