dbgassert
標準に似たマクロを作成しようとしていますassert
。何を行うかに加えて、任意の数の追加パラメーター (デバッグ情報を含む)を出力assert
したいと考えています。dbgassert
私がこれまでに持っているものを以下にリストします。これは、この SO answerから改作されています。しかし、可変個引数テンプレートまたはマクロのいずれかでコードに問題があります。少なくとも 1 つの追加の引数 (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'
}