Thomas Thomas - 25 days ago 5
C++ Question

How to make a better design if two overload functions are similar

I'm working on a c++ project and I have a case as below:


void func(int a, int b)
{
if (some_bool)
{
generateString(generateFunc()); // different
}
for (auto it : myVector)
{
// do something
for (int i = 0; i < a + b; ++i)
{
if (some_bool2)
{
myData = generateInt();
}
else
{
myData2 = generateInt2(); // different
}
}
}
}


void func(int a, int b, string str)
{
if (some_bool)
{
generateString(generateFunc(str)); // different
}
for (auto it : myVector)
{
// do something
for (int i = 0; i < a + b; ++i)
{
if (some_bool2)
{
myData = generateInt();
}
else
{
myData2 = convertStrToInt(str); //different
}
}
}
}


As you see, I have two overloading functions.

Their logical structures are the same but some details are not.


I'm considering if there is some technique which can merge them so that I can have a better design. Because for now I have to change two times if I need to do some change.

Answer

You can use templates and do something like this:

template<typename F, typename... A>
void func(int a, int b, F &&f, A&&... a)
{
    if (some_bool)
    {
        generateString(generateFunc(std::forward<A>(a)...));  // different
    }
    for (auto it : myVector)
    {
        // do something
        for (int i = 0; i < a + b; ++i)
        {
            if (some_bool2)
            {
                myData = generateInt();
            }
            else
            {
                myData2 = std::forward<F>(f)(std::forward<A>(a)...);  //different
            }
        }
    }
}

Then call your function as it follows:

func(0, 0, generateInt2);

// or

func(0, 0, convertStrToInt, std::string{0});