我有这样的代码:C++更好的方式来处理函数重载
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
}
}
为什么不把普通的30行放在单独的函数中? – Asha 2012-04-10 10:12:56
将30行常用代码放在一个单独的函数中,这个函数被'Foo'函数调用? – 2012-04-10 10:13:20