c++ - 访问宏中的变量值

标签 c++ macros

前段时间,我为 c 和 c++ 程序制作了这个漂亮的断言宏

#define ASSERT(truthy, message) \
     if (!(truthy)) \
     {\
         cout << message << " on line " << __LINE__ << " in file " << __FILE__ << ". Check was " << #truthy << endl;\
     }

在你的代码中分散 ASSERT 调用,当 truthy 值不真实时,它会警告你!在开发过程中非常方便,可以提醒您潜在的错误。

ASSERT(filesFound > 0, "Couldn't find any files, check your path!");

当filesFound为0时,宏会打印出来

Couldn't find any files, check your path! on line 27 in file openFiles.c. Check was filesFound > 0

现在我想要打印它,给我更多相关信息,是传递给truthy的任何变量的值范围。像这样

Couldn't find any files, check your path! on line 27 in file openFiles.c. Check was filesFound > 0, filesFound is 0

这似乎是 lisp 的领域,我想知道,是否有任何黑魔法 c 预处理可以用来评估变量和函数的值,而无需评估 truthy 语句?

我想我会失望的。

最佳答案

我一直使用的另一种解决方案是在宏中支持可变参数,然后强制断言用户指定相关的消息/变量 - 每次都需要做一些额外的工作,但从好的方面来说,你可以准确获取您想要的格式,并包含“真实”位中不可用的信息,例如:

#define ASSERT(truthy, message, ...) \
if (!(truthy)) \
{\
    MyAssertHandler(__LINE__, __FILE__, #truthy, message, ##__VA_ARGS__);
}

那么你的处理程序只是一个相当标准的 var-arg 函数,可以使用例如vsnprintf 生成消息并输出它,例如在我的脑海中浮现:

void MyAssertHandler(int line, const char* file, const char* expressionStr, const char* format, ...)
{
    // Note: You probably want to use vsnprintf instead to first generate
    //       the message and then add extra info (line, filename, etc.) to
    //       the actual output 
    va_list args;
    va_start(args, format);
    vprintf(format, args);
    va_end(args);

    // Log to bug database, DebugBreak() if a debugger is attached, etc.
}

用法:

ASSERT(IsBlah(), "BlahBlah: x = %.2f, name = %s", GetX(), GetName());

关于c++ - 访问宏中的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32779510/

相关文章:

c# - 将 C# 系统转换为跨平台应用程序的最佳编程语言?

c++ - 为什么我的 C++ 程序会打印一个额外的换行符?

c - 在 gcc 语句表达式中声明一个数组并返回指向它的指针?

c - 定义用于定义函数的宏

ios - IOS 8 中的预处理器宏和 bool 值未正确评估

c++ - 接收输入时运行后台循环 (C++)

c++ - 学习 Game Boy C++ 开发的好教程

c++ - SOCI 行集<行> 奇怪的错误

C++ 格式宏/​​内联 ostringstream

C++ #define可变参数函数