我的代码如下:
void Foo(int& a, string& b, vector<int>& c) {
... // 30 lines of code are same as another function
... // 10 lines of code to parse and assign value to vector<int>& c
}
void Foo(int& a, string& b, map<string, int>& d) {
... // 30 lines of code are same as another function
... // 10 lines of code to parse and assign value to map<string, int>& d
}
有没有办法避免重复那30行代码?在这种情况下我应该使用函数重载吗?
修改
如果代码不容易分开怎么办?像:
void Foo(int& a, string& b, vector<int>& c) {
for() {
if(m) ... // 30 lines of code are same as another function
else if(n) ... // 30 lines of code are same as another function
else if(o) ... // 30 lines of code are same as another function
else if(p) ... // 10 lines of 'vector<int>& c' code
else if(q) ... // 10 lines of 'vector<int>& c' code
}
}
void Foo(int& a, string& b, map<string, int>& d) {
for() {
if(m) ... // 30 lines of code are same as another function
else if(n) ... // 30 lines of code are same as another function
else if(o) ... // 30 lines of code are same as another function
else if(p) ... // 10 lines of 'map<string, int>& d' code
else if(q) ... // 10 lines of 'map<string, int>& d' code
}
}
答案 0 :(得分:6)
将30行重构为您在两个重载中调用的辅助函数。
编辑:如果代码差异太大而你正在努力将它分开,那么问题是什么?
答案 1 :(得分:4)
您可以分解公共代码:
void helper(int& a, string& b) {
... // 30 lines of common code
}
然后在函数中使用它:
void Foo(int& a, string& b, vector<int>& c) {
helper(a, b);
... // 10 lines of code to parse and assign value to vector<int>& c
}
void Foo(int& a, string& b, map<string, int>& d) {
helper(a, b);
. .. // 10 lines of code to parse and assign value to map<string, int>& d
}
或者,如果公共代码包含对容器的引用,则可以使用模板:
template<template<typename T, typename Alloc> class Container>
void helper(int& a, string& b, Container& d) {
... // 30 lines of common code
}
注意:您必须使用模板专精化,因为并非所有容器都具有相同的插入(或访问)方法(例如,矢量,列表:push_back
;地图:insert
)
更新:在OP添加更多代码后提问:
如果唯一的区别在于容器的处理,但容器处理的“精神”非常相似,你可以为容器创建(模板)包装器并将包装器传递给一个共同的功能:差异将会在包装器的不同实现中捕获。
答案 2 :(得分:0)
也许大多数常见的东西可以用迭代器来处理?