Yves
Yves

Reputation: 12371

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?

Upvotes: 5

Views: 1187

Answers (4)

Jarod42
Jarod42

Reputation: 217275

template may be a possibility:

template <typename ... Ts>
auto func(const Ts&... args)
-> decltype(sendMsg(args...), void()) // SFINAE to only allow correct arguments
{
    // piece of code A
    sendMsg(args...);
    // piece of code B
}

but moving // piece of code A in its own function would probably be my choice.

Upvotes: 15

mfnx
mfnx

Reputation: 3018

Another idea would be to give a default value to str:

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

Upvotes: 6

Dmitry
Dmitry

Reputation: 1339

Of course, use a functor:

template <typename F> void func2(F&& f) {
    // piece of code A
    f();
    // piece of code B
}

Usage:

void func(int a, char ch, double d) {
    func2([&](){ sendMsg(a, ch, d); });
}

A bit of explanation: Currently accepted answer is totally fine when you need to call the exactly same code with different parameters. But when you need to "inject" an arbitrary code (possibly a multiple pieces of arbitrary code) into another function, passing a temporary lambda is your best bet. Conceptually, what receiving function is seeing/getting is some abstract "callable" object (in fact, it can be anything with operator (), not just lambda) which it calls at due time. And since its a templated function, it will be compiled into zero-overhead code "as if" actual code was copy-pasted in there. The usage part is simply shows a c++ syntax to create a callable with arbitrary code in-place (I advise to read language references/tutorials on lambdas to understand the internals better).

Upvotes: 5

Tzig
Tzig

Reputation: 841

You would have to do something like

void codeA() {
    // ...
}

void codeB() {
    // ...
}

void func(const std::string& str, int a, char ch, double d) {
    codeA();
    sendMsg(str, a, ch, d);
    codeB();
}

void func(int a, char ch, double d) {
    codeA();
    sendMsg(a, ch, d);
    codeB();
}

Upvotes: 8

Related Questions