首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 泛型編程之 TypeLists:類型列表元編程基礎設施

     編輯:關於C++

TypeList 核心概念

TypeList 是一個**編譯時**的類型序列容器,不包含數值,僅攜帶類型信息。結構定義:

template 
struct TypeList {
    typedef Head Head;
    typedef Tail Tail;
};

struct NullType {}; // 終結符

線性化宏定義

便於聲明多類型列表:

#define TYPELIST_1(T1) TypeList
#define TYPELIST_2(T1,T2) TypeList
#define TYPELIST_3(T1,T2,T3) TypeList
// ... 以此類推

核心操作元函數

1. 長度 Length

template  struct Length;
template <> struct Length { enum { value = 0 }; };
template 
struct Length> {
    enum { value = 1 + Length::value };
};

2. 索引訪問 TypeAt

template  struct TypeAt;
template 
struct TypeAt, 0> { typedef Head Result; };
template 
struct TypeAt, i> {
    typedef typename TypeAt::Result Result;
};

3. 安全訪問 TypeAtNonStrict (越界返回默認類型)

template 
struct TypeAtNonStrict { typedef DefaultType Result; };
// ... 偏特化實現

4. 查找索引 IndexOf

template  struct IndexOf;
template  struct IndexOf { enum { value = -1 }; };
template 
struct IndexOf, T> { enum { value = 0 }; };
template 
struct IndexOf, T> {
private:
    enum { temp = IndexOf::value };
public:
    enum { value = temp == -1 ? -1 : 1 + temp };
};

5. 尾部追加 Append

template  struct Append;
// ... 多種偏特化處理 NullType、單類型、TypeList 等情況

6. 反轉 Reverse

template  struct Reverse;
template <> struct Reverse { typedef NullType Result; };
template 
struct Reverse> {
    typedef typename Append::Result, Head>::Result Result;
};

測試代碼片段

typedef TYPELIST_3(char, int, double) TL3;
static_assert(Length::value == 3);
static_assert(std::is_same::Result, int>::value);
static_assert(IndexOf::value == 2);
typedef Append::Result TL4; // char, int, double, float
static_assert(Length::value == 4);

應用場景

  • 為模板類自動生成構造函數參數列表。
  • 實現 Variant/Tuple 等異構容器。
  • 編譯時類型遍歷、過濾、轉換 (配合模板模式匹配)。
  • 現代 C++ (C++11+) 推薦使用 `std::tuple`、`std::variant` 和折疊表達式替代手寫 TypeList,但理解其原理有助於掌握模板元編程精髓。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved