[c++11]类型别名设置

参考:

Aliases and typedefs (C++)

Type aliases (typedef / using)

处于封装的目的,又或者是为了简化复杂度,经常会为已有类型声明一个新类型名

有两种方式实现:typedefusing

typedef

参考:typedef specifier

类型声明符typedef能够创建一个别名(alias),可以在任何地方使用它来代替(可能是复杂的)类型名。语法如下:

typedef old_type new_type;
  • 整数别名
typedef unsigned char uchar;
uchar a = 255;
cout << static_cast<int>(a) << endl;
# 输出
255
  • 指针别名
typedef char *pointer_char;
char ch = 'c';
pointer_char pCh = &ch;
cout << *pCh << endl;
# 输出
c
  • 结构体别名
typedef struct ss {
    int a;
} S, *pS;

int main() {
    struct ss test1;
    S test2;

    test1.a = 3;
    test2.a = 4;

    pS test3 = &test2;
    cout << test3->a << endl;

    return 0;
}

构造结构体ss,设置类型别名S和指针别名*pS

重定义

  • typedef允许在同一个作用域内有重复类型别名定义,但是必须是相同类型的设置
  • typedef允许在不同作用域内有相同类型别名,不同类型的重复定义
# name.h
typedef unsigned char uchar;
# main.cpp
#include "name.h"

typedef unsigned char uchar;

void main() {
    uchar c = 'c';

    typedef unsigned int uchar;

    uchar a = 3232;
    cout << a << endl;

    return 0;
}

using

参考:Type alias, alias template (since C++11)

c++11开始,同样可以使用using关键字设置类型别名。语法如下

using identifier = type;

示例如下:

using C = char;
using WORD = unsigned int;
using pChar = char *;
using field = char [50]; 

除了能够实现typedef的功能外,using的优势在于它能够和模板一起工作

# 创建别名模板
template<typename T> using ptr = T*;

// the name 'ptr<T>' is now an alias for pointer to T
ptr<int> ptr_int;
ptr<char> ptr_char;