别名
您可以使用别名声明来声明一个名字作为先前声明类型的同义词 (这种机制也将非正式称为类型别名). 您也可以使用这种机制来创建一个别名模版,它对定制的分配器尤其有用
using identifier = type;
备注
identifier
别名的名称。type
您为其创建别名的类型标识符。
别名不引入了一种新类型,并且不能更改现有类型名称的含义。
一个别名最简单的形式相似于C++03的typedef 机制:
// 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> struct MyAlloc {
typedef T value_type;
MyAlloc() { }
template <typename U> MyAlloc(const MyAlloc<U>&) { }
bool operator==(const MyAlloc&) const { return true; }
bool operator!=(const MyAlloc&) const { return false; }
T * allocate(const size_t n) const {
if (n == 0) {
return nullptr;
}
if (n > static_cast<size_t>(-1) / sizeof(T)) {
throw std::bad_array_new_length();
}
void * const pv = malloc(n * sizeof(T));
if (!pv) {
throw std::bad_alloc();
}
return static_cast<T *>(pv);
}
void deallocate(T * const p, size_t) const {
free(p);
}
};
#include <vector>
using MyIntVector = std::vector<int, MyAlloc<int>>;
#include <iostream>
int main ()
{
MyIntVector foov = { 1701, 1764, 1664 };
for (auto a: foov) std::cout << a << " ";
std::cout << "\n";
return 0;
}