How to use generic types in macro function arguments

Viewed 124

I want to make a test library for c++

So I have defined this macro

#define TEST_CHECK(cond) check(cond,__FILE__,__LINE__,"%s",#cond)

And implemented check(...) as:

int check(int cond, const char* file, const char* line, const char* fmt, ...){
    // ...
    if(cond){printf("test passed");}
    else{ printf("test failed");}
    // ...
}

It is working okay, I can, for example use it as follows

TEST_CHECK(max(1,2)==1);

test failed

TEST_CHECK(max(-2,-3)==-2);

test passed


But now I would like to print the expected and the observed result, instead of only printing text failed.

So an execution example would be

TEST_CHECK(max(2,3),3);

test failed: expected 3 but got 2

I could change my function to check(int expected, int observed ...) and it would work. But in that case I would be fitting only for INTEGER validation. I would also want to make this function useful for double,float, bool, char, char[], int[],...).

How could I solve this?

1 Answers

You can use a template function.

template <typename T>
void check (T expected, T observed)
{
    if (expected == observed)
        std::cout << "Test passed\n";
    else
        std::cout << "Test failed: Expected " << expected 
                  << "but got " << failed << std::endl;
}
Related