2012-04-10 52 views
2

我有這樣的代碼: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 
    } 
} 
+0

爲什麼不把普通的30行放在單獨的函數中? – Asha 2012-04-10 10:12:56

+0

將30行常用代碼放在一個單獨的函數中,這個函數被'Foo'函數調用? – 2012-04-10 10:13:20

回答

4

你可以分解出公共代碼:

void helper(int& a, string& b) { 
    ... // 30 lines of common code 
} 

然後使用,在功能:

​​

另外,如果通用代碼包含對容器的引用,以及你可以使用模板:

template<template<typename T, typename Alloc> class Container> 
void helper(int& a, string& b, Container& d) { 
    ... // 30 lines of common code 
} 

注意:您將不得不使用模板專業化,因爲不是所有CONTA iners具有相同的插入(或訪問)方法(例如,矢量,列表:push_back;圖:insert

UPDATE:後OP增加了更多的代碼問題:

如果唯一的區別是在集裝箱的裝卸,但的集裝箱裝卸「精神」是非常相似的,你可以創建(模板)包裝器,並將包裝器傳遞給一個通用函數:差異將在包裝器的不同實現中捕獲。

6

重構的30行到你在這兩個重載調用輔助功能。

編輯:如果代碼不同以至於難以分開它,那麼問題是什麼?

0

也許大部分常見的東西都可以用迭代器來處理?

相關問題