25-模板别名(C++11)
14.4.10 模板别名(C++11)
如果能为类型指定别名,将很方便,在模板设计中尤其如此。可使用typedef为模板具体化指定别名:
// define three typedef aliases
typedef std::array<double, 12> arrd;
typedef std::array<int, 12> arri;
typedef std::array<std::string, 12> arrst;
arrd gallons; // gallons is type std::array<double, 12>
arri days; // days is type std::array<int, 12>
arrst months; // months is type std::array<std::string, 12>
但如果您经常编写类似于上述typedef的代码,您可能怀疑要么自己忘记了可简化这项任务的C++功能,要么C++没有提供这样的功能。C++11新增了一项功能——使用模板提供一系列别名,如下所示:
template<typename T>
using arrtype = std::array<T,12>; // template to create multiple aliases
这将arrtype定义为一个模板别名,可使用它来指定类型,如下所示:
arrtype<double> gallons; // gallons is type std::array<double, 12>
arrtype<int> days; // days is type std::array<int, 12>
arrtype<std::string> months; // months is type std::array<std::string, 12>
总之,arrtype
C++11允许将语法using =用于非模板。用于非模板时,这种语法与常规typedef等价:
typedef const char * pc1; // typedef syntax
using pc2 = const char *; // using = syntax
typedef const int *(*pa1)[10]; // typedef syntax
using pa2 = const int *(*)[10]; // using = syntax
习惯这种语法后,您可能发现其可读性更强,因为它让类型名和类型信息更清晰。
C++11新增的另一项模板功能是可变参数模板(variadic template),让您能够定义这样的模板类和模板函数,即可接受可变数量的参数。这个主题将在第18章介绍。