2016-08-21 196 views
2

我有兩個函數只有一個參數(不同的結構),差不多相同的處理,導致大量的代碼重複不同。請參閱下面的簡單示例:減少代碼重複

struct foo { 
    int a; 
}; 

struct bar { 
    int a; 
    int b; 
}; 

foo(struct foo *f) { 
    do_b(); 
    // error handling 
    f->a = 1; 
    do_c(); 
    // error handling 
    do_d(); 
    // error handling 
} 

bar(struct bar *b); { 
    do_a(); 
    // error handling 
    b->b = 2; 
    do_b(); 
    // error handling 
    b->a = 1; 
    do_c(); 
    // error handling 
    do_d(); 
    // error handling 
} 

有僅使用一個功能消除了重複代碼一些聰明的方法是什麼?

+5

你願意改變'結構B'爲'結構B {結構A中的; int b; };'? –

+3

真正聰明的做法是要完全理解[嚴格別名規則](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule)。不幸的是,沒有人理解這個規則([示例](https://stackoverflow.com/questions/39035426/is-aliasing-of-pointers-between-aggregate-c-structs-and-their-members-standards),[示例](https://stackoverflow.com/questions/39036857/opaque-structures-with-multiple-definitions),[示例](https://stackoverflow.com/questions/38968296/a-type-for-arbitrary-存儲器中-C/38969259#38969259))。所以你有點卡住了。 – user3386109

回答

4

是的,但不是你想象的方式。保持類型安全性是非常有益的,並且擺脫它是不符合您的最佳利益的(使用指向void或struct結構的指針)。

如果您有兩種不同的類型因爲某些有意義的原因被定義爲不同的類型,那麼應有有兩個單獨的函數可以採用這些類型。

你應該在這種情況下做的,就是消除這些功能裏面的重複:

first(int* a) 
{ 
    do_b(); 
    // error handling 
    *a = 1; 
    do_c(); 
    // error handling 
    do_d(); 
    // error handling 
} 

foo(struct foo *f) { 
    first(&f->a); 
} 

bar(struct bar *b); { 
    do_a(); 
    // error handling 
    b->b = 2; 
    first(&b->a); 
}