曲径通幽论坛

标题: 模板别名 [打印本页]

作者: easy    时间: 2013-12-24 18:10
标题: 模板别名
可以使用 typedef 为模板具体化指定别名,比如:
[C++] 纯文本查看 复制代码

typedef std::array<double, 12> arrd;
typedef std::array<int, 12> arri;
typedef std::array<std::string, 12> arrst;
arrd gallons;  // gallons 是 std::array<double, 12> 类型
arri days;     // days 是 std::array<int, 12> 类型
arrst months;  // months 是 std::array<std::string, 12> 类型


C++11 新增了一项功能 --- 使用模板提供一系列别名。比如:
  1. template<typename T>
  2. using arrtype = std::array<T,12>;  //可用来创建多个别名的模板
复制代码
这样,arrtype 就被定义为一个模板别名,可使用它来指定类型,比如:
  1. arrtype<double> gallons;   // gallons 是 std::array<double, 12> 类型
  2. arratype<int> days;    //days 是 std::array<int, 12> 类型
  3. arrtype<std::string> months;     // months 是 std::array<std::string, 12> 类型
复制代码
总之,arrtype<T> 表示类型 std::array<T, 12> 。

C++11 允许将语法 using = 用于非模板。用于非模板时,这种语法与常规的 typedef 等价:
  1. typedef const char * pc1;       // typedef 语法
  2. using pc2 = const char *;       // using = 语法
  3. typedef const int *(*pa1)[10];  // typedef 语法
  4. using pa2 = const int *(*)[10]; // using = 语法
复制代码
当习惯这种语法后,你可能会觉得这个可读性更强,因为它让类型名和类型信息更清晰





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2