简体   繁体   English

如何在宏 function arguments 中使用泛型类型

[英]How to use generic types in macro function arguments

I want to make a test library for c++我想为 c++ 做一个测试库

So I have defined this macro所以我定义了这个宏

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

And implemented check(...) as:并将check(...)实现为:

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测试失败:预期为 3,但得到了 2

I could change my function to check(int expected, int observed...) and it would work.我可以将我的 function 更改为check(int expected, int observed...)并且它会起作用。 But in that case I would be fitting only for INTEGER validation.但在那种情况下,我只适合 INTEGER 验证。 I would also want to make this function useful for double,float, bool, char, char[], int[],...).我还想让这个 function 对 double、float、bool、char、char[]、int[]、...) 有用。

How could I solve this?我怎么能解决这个问题?

You can use a template function.您可以使用模板 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM