dimanche 5 décembre 2021

How to pass functions with different signatures as parameter to other function

I'm struggling with the following problem and if this has been asked, I apologize.

I have multiple parts in my code doing a similar job - they mainly differ in a function call:

int doSomething(string* s, int i) {
  ...
}

int doSomethingOther(string* s, string t) {
  ...
}

int main() {
  int num;
  string s;

  // do something with num
 
  // repeating part start
  string str1;

  // do some stuff
  
  int res1 = doSomething(&str1, num);

  cout << "res: " << res1 << " str1: " << str1 << endl;
  // end

  // do something with s
  
  // here we go again but with a different function call
  string str2;

  // do some stuff

  int res2 = doSomethingOther(&str2, s);

  cout << "res: " << res2 << " str2: " << str2 << endl;
  //end
  
  return 0;
}

Is it possible to define a general function to reduce the writing effort? One possibilityis using a parameter for this common function indicating which function should be used. On the other hand if the called function was always the same, it would be also possible by using a function pointer:

...
void generalFct(int p, int(*doSomethingFct)(string* aString, int anInt)) {
  string s;

  // do some stuff

  int res = (*doSomethingFct)(&s, p);

  cout << "res: " << res << " s: " << s << endl;

  // do some other stuff
}
...
int main() {
  int num;

  // do something with num

  generalFct(num, &doSomething);

  ...
  
  // update num...

  generalFct(num, &doSomething);
}

But unfortunately the signature of doSomething and doSomethingOther differs (otherwise that would be a solution) and that's where I stuck. Is there any kind of technique that helps me to achieve my goal, i.e. something like that:

int main() {
  int num;

  // do something with num

  generalFct(num, &doSomething);

  ...
  
  // update num...

  generalFct(num, &doSomethingOther);
}

Aucun commentaire:

Enregistrer un commentaire