Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce the redundant code in a header file?

Tags:

c++

dry

I'm writing unit tests to test C++ classes. The functions below test to see how a function handles an exception. The code below does work, but it is very redundant, I would prefer to have 1 template function rather than many repetitive ones. There also needs to be tests for functions that return strings and that will increase the number of template functions as well.

I've read the cpp reference for pack and I don't really see anything that relates to what I'm trying to do. I've also looked through 40 questions on SO.

Is there any way to reduce or eliminate the redundant code in these functions.

    bool testExceptionAndSuccess(std::function<bool()>funcUnderTest)
    {
        forceException = true;
        if (funcUnderTest())
        {
            return testExceptionReportFailure(false, true, "testExceptionAndSuccess");
        }

        forceException = false;
        return funcUnderTest();
    }

    template <typename T>
    bool testExceptionAndSuccess1Arg(std::function<bool(T)>funcUnderTest, T arg1)
    {
        forceException = true;
        if (funcUnderTest(arg1))
        {
            return testExceptionReportFailure(false, true, "testExceptionAndSuccess1Arg");
        }

        forceException = false;
        return funcUnderTest(arg1);
    }

    template <typename T, typename U>
    bool testExceptionAndSuccess2Arg(std::function<bool(T, U)>funcUnderTest, T arg1, U arg2)
    {
        forceException = true;
        if (funcUnderTest(arg1, arg2))
        {
            return testExceptionReportFailure(false, true, "testExceptionAndSuccess2Arg");
        }

        forceException = false;
        return funcUnderTest(arg1, arg2);
    }
like image 220
pacmaninbw Avatar asked Dec 03 '25 21:12

pacmaninbw


1 Answers

std::function is unneeded and just does harm here, you might do:

template <typename F, typename... Ts>
bool testExceptionAndSuccessNArgs(F funcUnderTest, Ts... args)
{
    forceException = true;
    if (funcUnderTest(args...))
    {
        return testExceptionReportFailure(false, true, "testExceptionAndSuccessNArgs");
    }
    forceException = false;
    return funcUnderTest(args...);
}
like image 73
Jarod42 Avatar answered Dec 05 '25 12:12

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!