c++ - 如何创建一个宏来验证 HR 和日志?

标签 c++

我在代码中有一个场景,其中存在以下模式 -

if (!function(A))
{
   log("this is the %d error in this file called %s", num, fileName);
   throw AppException(FUNCTION_ERROR);
}

这个问题是你需要一直这样做,而且代码看起来很脏。所以我想定义一个宏 -

#define VerifyOrThrow(b, retcode, logerror)
        if (b == 0)                                         \
        {                                                   \
            log(logerror,arg1, arg2)  -->this is the issue        \
            throw(AppException(retcode));                   \
        }

然后我可以像这样在一行中使用它

VerifyOrThrow(functionA(), FUNCTION_ERROR,this is the %d error in this file called %s);

问题是我不确定如何为日志字符串的可变长度参数定义宏。

有什么想法吗?

最佳答案

使用 __VA_ARGS__ 作为:

#define VerifyOrThrow(b, retcode, ...)
        if (b == 0)                                         \
        {                                                   \
            log(__VA_ARGS__);                               \
            throw(AppException(retcode));                   \
        }

关于c++ - 如何创建一个宏来验证 HR 和日志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5788043/

相关文章:

c++ - 如何让 Armadillo 在 Windows 上工作?

c++ - 方法参数中的动态类型匹配

C++ IPv6端口问题

c++ - 如何在 OpenCV 中混合多个图像?

c++ - 为什么 __m256 而不是 'float' 提供超过 x8 的性能?

c++ - 导出命名空间之后的所有内容都没有导出吗?

c++ - 使用 cmath 的 fmod (C++) 时的不一致

c++ - 如何证明Copy Constructor是强制的

c++ - 什么是 'valid' std::function?

c++ - 读入一个文件并将其分成 100 个较小的文件非常慢