mercredi 4 août 2021

How to avoid code duplication with function overloading

I have a pair of overloaded functions:

void func(const std::string& str, int a, char ch, double d) {
    // piece of code A
    sendMsg(str, a, ch, d);
    // piece of code B
}

void func(int a, char ch, double d) {
    // piece of code A
    sendMsg(a, ch, d);
    // piece of code B
}

piece of code A and piece of code B are exactly the same, the only difference is the parameter of sendMsg.

Is there some way to avoid the code duplication?

About answers

I take @mfnx's answer because it's quite simple and clear. Others are great too especially the template one and the lambda one.

Making another two functions for A and B is OK too but it's not suitable for my case...

Aucun commentaire:

Enregistrer un commentaire