Class Templates
A class template is a blueprint for generating classes.
Class Templates
Defining a Class Template
we'll implement a template version of StrBlob
template <typename T>
class Blob{
public:
private:
std::shared_ptr<std::vector<T> > data;
};Like function templates, class templates begin with the key template followed by a template parameter list.
- 在class 关键字前声明模板头(template 关键字 + 模板参数列表);
- 在class 内 使用模板参数定义数据成员、函数参数、函数返回类型
使用模板类型参数定义了 数据成员data
Instantiating a Class Template
We must supply extra information.
extra information is a list of explicit template arguments that are bound to the template's parameters.
使用类模板时必须显式地提供模板参数
Blob<int> ia;使用cppinsights转换的结果:
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class Blob<int>
{
public:
private:
std::shared_ptr<std::vector<int, std::allocator<int> > > data;
public:
// inline constexpr Blob() noexcept = default;
// inline ~Blob() noexcept = default;
};
Blob<int> ia = Blob<int>();在使用class template 时,编译器首先使用提供的模板参数生成对应的类,类中使用到了模板参数的地方全部替换为实际参数。然后再用生成的类实例化对象。
提供不同的参数类型,compiler instantiates 出不同的类,由同一个类模板 instantiate 出来的所有类(模板类)是独立的。
Reference to a Template Type in the Scope of the template
it can be helpful to remember that the name of a class template is not the name of a type.
Whenever we use a template, we must supply template arguments.
类模板的名称不是类型名,没办法只使用类模板的名称作为对象的类型,必须提供模板参数。
不能直接使用Blob,而是要使用Blob<T>
将Blob<T> 当作一个类型进行使用
Member Functions of Class Template
A class template member function is itself an ordinary function.
As with any class, we can define the member functions of a class template either inside or outside of the class body.
As usual, when we define a member outside its class, we must say to which class the member belongs.
Also as usual, the name of a class generated from a template includes its template arguments.
类外定义member functions 时需要带上模板参数
template <typename T>
void Blob<T>::check(size_t i, const std::string &msg) const
{
if(i >= data->size())
throw std::out_of_range(msg);
}类名是Blob<T>
定义模板类的对象时提供了模板参数,所以不需要template 声明。如果没有提供实际的模板参数,就需要template 声明,即使check()没有使用模板参数。这里templte 声明是为了给Blob<T>提供模板参数。
假设有两个模板类对象,提供的模板参数类型分别是int、double,类外访问时需要区分当前定义的是Blob<int> 还是 Blob<double>
cppinsights 生成的check
void check(size_t i, const std::basic_string<char> & msg) const;instantiating 后模板参数被替换,和普通成员函数没有区别。
问:class template 内能否定义模板参数,如果可以如何在类外定义?
问:不能定义同名但是模板参数列表不同(数量)的类,那类外定义member functions 是否可以不带template parameters呢?(通过类名就能确认是哪个模板类)