1. 程式人生 > >C語言用巨集實現靜態多型

C語言用巨集實現靜態多型

綜述

多型性是面向物件程式設計的一個重要特徵。

在C++語言中,多型指的是:具有不同功能的函式可以用同一個函式名,可以用一個函式名呼叫不同內容的函式。

C++的多型分為兩種:

1. 靜態多型性(編譯時多型):在程式編譯時系統就能決定呼叫的是哪個函式,因此稱為編譯時多型性

2. 動態多型性:在程式執行過程中才動態確定操作指標指向的物件,又被稱為執行時多型

C++實現多型可以用虛擬函式,抽象類,覆蓋以及模板實現

C語言是面向過程的語言,但同樣可以實現多型性,可以通過巨集實現編譯時多型,用函式指標實現動態多型

C語言用巨集實現編譯時多型

例如以下例子是用巨集實現雙向連結串列的一部分

#include <stdio.h>
#include <stdlib.h>

#define INIT_LIST_TYPE(type)                    \
    typedef struct list_element_##type {        \
        struct list_element_##type* next, *pre; \
        void* val;                              \
    } list_element_##type;                      \
    typedef struct list_head_##type {           \
        list_element_##type* elem, *last;       \
        int length;                             \
    } list_head_##type;

#define list_element(type) \
    list_element_##type

#define list_head(type) \
    list_head_##type

#define LIST_FUNC_DECLARE(type)   \                                                          
    list_head_##type* init_list_##type();
                                                   
#define LIST_FUNC_INIT(type)   \
    _init_list(type)           
#define init_list(type) init_list_##type()

#define _init_list(type)                                                              \
    list_head_##type* init_list_##type()                                              \
    {                                                                                 \
        list_head_##type* h = (list_head_##type*)calloc(1, sizeof(list_head_##type)); \
        h->last = h->elem = NULL;                                                     \
        h->length = 0;                                                                \
        return h;                                                                     \
    }

#endif

呼叫

INIT_LIST_TYPE(int);
LIST_FUNC_INIT(int);

INIT_LIST_TYPE(float);
LIST_FUNC_INIT(float);


#define context_bam_elem list_element(int)
#define list_head_t list_head(int)

#define list_element_f_t list_element(float)
#define list_head_f_t list_head(float)


int main()
{
    list_head_t* h = init_list(int);
    list_head_f_t* h1 = init_list(float);
    
    return 0;
}