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