繁体   English   中英

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

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

我想为 c++ 做一个测试库

所以我定义了这个宏

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

并将check(...)实现为:

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

它工作正常,例如,我可以按如下方式使用它

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

测试失败

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

考试通过了


但现在我想打印预期和观察到的结果,而不是只打印文本失败。

所以一个执行示例是

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

测试失败:预期为 3,但得到了 2

我可以将我的 function 更改为check(int expected, int observed...)并且它会起作用。 但在那种情况下,我只适合 INTEGER 验证。 我还想让这个 function 对 double、float、bool、char、char[]、int[]、...) 有用。

我怎么能解决这个问题?

您可以使用模板 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