簡體   English   中英

ANSI C:如何在結構域上進行抽象?

[英]ANSI C : How do I abstract over over struct fields?

我有一個圖像表示為RGB像素的2D數組。

typedef struct {
    char R;
    char G;
    char B;
} RGB;

以及為該圖像計算每個像素的新顏色的函數:

RGB new_color(RGB image[][], int r, int c){
    RGB color;
    color.R = image[r][c].R + image[r+1][c].R + image[r-1][c].R + image[r][c+1].R + image[r][c-1].R;
    color.G = image[r][c].G + image[r+1][c].G + image[r-1][c].G + image[r][c+1].G + image[r][c-1].G;
    color.B = image[r][c].B + image[r+1][c].B + image[r-1][c].B + image[r][c+1].B + image[r][c-1].B;
    return color;
}

是否可以刪除new_color正文中的代碼重復? 換句話說,抽象出RGB數據結構的字段名稱?

我們暫時忽略RGB image[][]在C89中是不合法的。

您可以分解訪問者功能。

char *get_RGB_R(RGB* rgb) { return &rgb->R; }
char *get_RGB_G(RGB* rgb) { return &rgb->G; }
char *get_RGB_B(RGB* rgb) { return &rgb->B; }

然后編寫一個使用它們的輔助函數。

void set_color_channel_from_adjacent(
    char *(*accessor)(RGB*), RGB* result, RGB image[][], int r, int c)
{
    *accessor(result) = *accessor(&image[r][c]) +
                        *accessor(&image[r+1][c]) + 
                        *accessor(&image[r-1][c]) + 
                        *accessor(&image[r][c+1]) + 
                        *accessor(&image[r][c-1]);
}

然后調用輔助函數

RGB new_color(RGB image[][], int r, int c)
{
    RGB color;
    set_color_channel_from_adjacent(get_RGB_R, &color, image, r, c);
    set_color_channel_from_adjacent(get_RGB_G, &color, image, r, c);
    set_color_channel_from_adjacent(get_RGB_B, &color, image, r, c);
    return color;
}

現代編譯器將內聯短函數並生成與原始函數等效的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM