2012-04-10 50 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

也许大部分常见的东西都可以用迭代器来处理?

相关问题