author: hjjdebug
date: 2025年 05月 28日 星期三 12:54:25 CST
descrip: c/c++類型別名定義:
文章目錄
- 1. #define 是宏替換.
- 2. c風格的typedef 通用形式 typedef type_orig alias
- 3. c++風格的using 為類型定義別名的一般格式: using alias = type_orig
- 4. using 的優點: 可以直接使用模板類型,
- 5.測試代碼, 順便測試一下引用折疊.
#define, typedef, using 都可以定義類型別名.
1. #define 是宏替換.
它可以定義任何東西,不只是類型,實現以簡單換復雜.
帶參宏也可以定義非常復雜的替換.
缺點是編譯器只是進行字符串替換. 編譯期無類型檢查.復雜定義時邏輯不清晰,
c格式的typedef和c++格式的using 才是專門為類型定義別名而生.
2. c風格的typedef 通用形式 typedef type_orig alias
例如:
typedef unsigned int u_int;
typedef int(*add)(int i1,int i2);
3. c++風格的using 為類型定義別名的一般格式: using alias = type_orig
例如:
using u_int=unsigned int;
using add=int(*)(int i1,int i2);
4. using 的優點: 可以直接使用模板類型,
例如:
template
using Vec = std::vector;
typedef 不能直接使用模板類型.
例如:
template
typedef T&& doubleR; // error: template declaration of ‘typedef’
typedef 要想使用模板類型,只能外包裝一個類才可以使用.
例如:
template
struct DoubleRefHelper {
typedef T&& type; // 在類模板中用typedef定義別名, 小名type是屬于類的.
};
5.測試代碼, 順便測試一下引用折疊.
$ cat main.cpp
#include <stdio.h>
//模板類中, using 更方便,可直接使用模板類型, typedef還要定義在類模板中
template <typename T>
using DoubleRef = T&&; //T 可以直接使用/*template <typename T>typedef T&& doubleR; // error: template declaration of ‘typedef’*/
template <typename T>
struct DoubleRefHelper {typedef T&& type; // 在類模板中用typedef 使用模板類型定義別名
};int main()
{ //引用類型推導規則.DoubleRef<int> x = 3; // int + &&實際類型為 int&&(折疊后)DoubleRef<int&> y = x; // int & + &&實際類型為 int&(折疊后)DoubleRef<int&&> z = 5; // int && + &&實際類型為 int&&(折疊后)printf("x:%d,y:%d,z:%d\n",x,y,z);// 使用時需加class_name和::type, 小名type是屬于類的.DoubleRefHelper<int>::type i = 8; // 等價于int&&printf("i:%d\n",i);return 0;
}
執行結果:
$ ./tt
x:3,y:3,z:5
i:8