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
}
有僅使用一個功能消除了重複代碼一些聰明的方法是什麼?
你願意改變'結構B'爲'結構B {結構A中的; int b; };'? –
真正聰明的做法是要完全理解[嚴格別名規則](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