gpt4 book ai didi

C++ 处理函数重载的更好方法

转载 作者:太空狗 更新时间:2023-10-29 23:41:33 25 4
gpt4 key购买 nike

我有这样的代码:

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 行重构为您在两个重载中调用的辅助函数。

编辑:如果代码差异很大,您很难将其分开,那么问题出在哪里?

关于C++ 处理函数重载的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10086787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com