gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:21:57 26 4
gpt4 key购买 nike

前段时间,我为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com