Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ better way to handle function overloading

I have code like:

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
}

Is there any way to avoid repeat that 30 lines of code? Should I use function overloading in this case?



EDIT:

What if the code is not easy to separate out? Like:

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
  }
}
like image 485
Stan Avatar asked Dec 21 '25 11:12

Stan


1 Answers

Refactor the 30 lines into a helper function you call in both overloads.

Edit: If the code is different enough that you're struggling to separate it, then what's the problem?

like image 89
Puppy Avatar answered Dec 24 '25 01:12

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!