【发布时间】:2012-08-01 05:37:42
【问题描述】:
我的应用程序使用标准输出之外的另一个输出来记录信息,这就是我编写自己的Log()、Error()、Panic() 和Assert() 函数的原因。为了更好地组织事情,我将所有调试内容都包含在 Debug 命名空间中。
Assert() 函数还提供源文件和行号会更有意义,这只能使用 __LINE__ 和 __FILE__ 宏。然而,总是不得不指定这两个参数是非常不愉快、低效的等等。
这就是我的代码的样子:
namespace Debug {
void Assert (int condition, std::string message, std::string file, int line);
}
我的问题是,是否可以在 Debug 命名空间内放置一个包含这两个参数的宏?像这样:
namespace Debug {
void Assert_ (int condition, std::string message, std::string file, int line);
#define Assert(a,b) Assert_(a, b, __FILE__, __LINE__)
}
// .... Somewhere where I call the function ....
Debug::Assert (some_condition, "Some_condition should be true");
// Output: Assertion failed on line 10 in file test.cpp:
// Some_condition should be true
这是有效的 c++ 吗?如果没有,有什么办法可以做到这一点?
【问题讨论】:
-
这会起作用,但宏不是命名空间的一部分。
-
@PaulR 所以换句话说,如果我省略了
Debug::,宏仍然可以工作吗? -
不 - 你仍然需要命名空间前缀(因为你所做的只是在预处理器中将
Assert转换为Assert_) - 问题是如果你在命名空间之外使用Assert那么它仍然会被翻译,这可能不是你想要发生的。
标签: c++ macros namespaces