C++ How to simplify member functions that only differ in function call

114 Views Asked by At

I need to create 10 functions that are very long and identical in every way except for a single line of code in each function. This single line of code is a function call. Is there a way to condense into one function? ex.

int doSomethingOne()
{
...
one();
...
}

int doSomethingtwo()
{
... // same as one
two();
... // same as one
}
2

There are 2 best solutions below

10
Ted Lyngmo On

You could create a function template doing all the common parts and calling a user-provided function in the middle of it all:

#include <iostream>

template <class Func>
int doSomething(Func&& func) {
    // do all the common stuff before calling func
    func();
    // do all the common stuff after calling func
    return 0;
}

void one() { std::cout << "One\n"; }
void two() { std::cout << "Two\n"; }

int doSomethingOne() { return doSomething(&one); }
int doSomethingtwo() { return doSomething(&two); }

int main() {
    doSomethingOne();
    doSomethingtwo();
    doSomething(+[]{ std::cout << "Anything goes\n"; });
}

Output:

One
Two
Anything goes
0
Jarod42 On

[..] that are very long and identical

You might create sub-functions, so

Data preamble()
{
    // ...
}
void postamble(Data& data)
{
    // ...
}

int doSomethingOne()
{
    auto data = preamble();
    one();
    postamble(data);
}

int doSomethingtwo()
{
    auto data = preamble();
    two();
    postamble(data);
}