2016-08-21 192 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); 
}