【发布时间】:2014-09-17 15:25:48
【问题描述】:
我正在尝试编写一个类似于标准assert 的宏dbgassert。除了assert 所做的,我还想dbgassert 打印任意数量的附加参数(包含调试信息)。
我目前掌握的内容如下,改编自this SO answer。但是我在代码中遇到了可变参数模板或宏的问题。如果我使用至少一个附加参数(OK 行),那么 dbgassert 将按预期工作。但是如果我没有给出额外的论点,那么编译就会失败(问题行)。
我有一些可变参数模板编程的经验(例如如何打印元组),但我之前没有使用过可变参数宏。
有人能解释一下编写这个可变参数宏组合的正确方法是什么吗?
顺便说一句,有人能解释一下宏中的#EX 魔法吗?它显示了表达式并在 gcc4.8.1 上为我工作。是否普遍支持?
谢谢,
代码:
//corrected reserved identifier issue and assumption issues per comments
#include <cassert>
#include <iostream>
using namespace std;
template <typename ...Args>
void realdbgassert(const char *msg, const char *file, int line, Args ... args) {
cout << "Assertion failed! \nFile " << file << ", Line " << line << endl
<< " Expression: " << msg << endl;
std::abort();
}
#define dbgassert(EX,...) \
(void)((EX) || (realdbgassert (#EX, __FILE__, __LINE__, __VA_ARGS__),0))
int main() {
dbgassert(1>2,"right","yes"); //OK
dbgassert(1>2,"right"); //OK.
//dbgassert(1>2); //Problem. compile error: expected primary-expression before ')' token
//#define dbgassert(EX,...) (void)((EX) || (realdbgassert (#EX, __FILE__, __LINE__, __VA_ARGS__)^,0))
}
代码的原始版本。
#include <cassert>
#include <sstream>
using namespace std;
#ifdef __cplusplus
extern "C" {
#endif
extern void __assert (const char *msg, const char *file, int line);
#ifdef __cplusplus
};
#endif
template <typename ...Args>
void _realdbgassert(const char *msg, const char *file, int line, Args ... args) {
stringstream os;
//... do something
__assert(msg,file,line);
}
#define dbgassert(EX,...) (void)((EX) || (_realdbgassert (#EX, __FILE__, __LINE__, __VA_ARGS__),0))
int main() {
dbgassert(1==0,"right"); //Problem line: undefined reference to `__assert'
}
【问题讨论】:
-
您正在使用reserved identifiers。无论如何,
__assert是什么?当然不是标准功能。还是您只是想使用您的实现没有的实现细节? -
.../ccZ47ZOL.o:test7.cpp:.text$_Z14_realdbgassertIIPKcEEvS1_S1_iDpT_[_Z14_realdbgassertIIPKcEEvS1_S1_iDpT_]+0x65): undefined reference to __assert' -
@TingL 好吧,你期待什么?您尚未提供
__assert的定义。还是说你的标准库实现提供了这样的功能? -
我认为
__assert是assert函数背后的函数。我在这里看到它:stackoverflow.com/questions/9701229/… -
我觉得标准的assert不可能是真正的函数,
assert宏后面一定有真正的函数吧?因为assert报告问题行,如果assert是一个真正的函数,它会报告<cassert>中的行号。标准中是否没有标准处理程序(即真正的断言函数)?
标签: c++ c++11 assert variadic-templates variadic-macros