C++:别名和 typedef
简介
可以使用 别名声明 来声明一个名称,用作之前声明的类型的同义词。 (这种机制也称为 " 别名) 类型 。 你还可以使用此机制来创建 别名模板,该模板对于自定义分配器特别有用。
语法
using identifier = type;
备注
identifier
别名的名称。
type
您为其创建别名的类型标识符。
别名未引入新类型,且无法更改现有类型名称的含义。
别名的最简单形式与 typedef c + + 03 中的机制等效:
// C++11
using counter = long;
// C++03 equivalent:
// typedef long counter;
二者都支持创建“计数器”类型的变量。 对于 std::ios_base::fmtflags 而言,像这样的类型别名会更有用:
// C++11
using fmtfl = std::ios_base::fmtflags;
// C++03 equivalent:
// typedef std::ios_base::fmtflags fmtfl;
fmtfl fl_orig = std::cout.flags();
fmtfl fl_hex = (fl_orig & ~std::cout.basefield) | std::cout.showbase | std::cout.hex;
// ...
std::cout.flags(fl_hex);
别名还能使用函数指针,但其可读性比等效的 typedef 更多:
// C++11
using func = void(*)(int);
// C++03 equivalent:
// typedef void (*func)(int);
// func can be assigned to a function pointer value
void actual_function(int arg) {
/* some code */ }
func fptr = &actual_function;
机制的限制 typedef 是不能用于模板。 但是,C++11 中的类型别名语法支持创建别名模板:
template<typename T> using ptr = T*;
// the name 'ptr<T>' is now an alias for pointer to T
ptr<int> ptr_int;
示例
以下示例说明如何将别名模板与自定义分配器一起使用 - 在此示例中,它是一个整数矢量类型。 您可以替换的任何类型 int 来创建一个方便的别名,以便在主功能代码中隐藏复杂的参数列表。 通过在代码中使用自定义分配器,您可以提高可读性并降低引入由拼写错误导致的 Bug 的风险。
#include <stdlib.h>
#include <new>
template <typename T>