是否可以在c ++中的命名空间中放置一个宏? [英] Is it possible to place a macro in a namespace in c++?

查看:169
本文介绍了是否可以在c ++中的命名空间中放置一个宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用另一个输出比标准输出的日志信息,这就是为什么我写了自己的 Log() Error / code>, Panic() Assert()为了更好地组织事物,我将所有的调试信息都放在 Debug 命名空间中。

My application uses another output than the standard output for logging information, which is why I wrote my own Log(), Error(), Panic() and Assert() functions. To organize things nicely, I enclose all the debugging stuff in a Debug namespace.

Assert()函数也提供一个源文件和行号,这只能使用 __ LINE __ code> __ FILE __ 宏。但是,它是相当不愉快,低效等...总是必须指定这两个参数。

It would make more sense for the Assert() function to also provide a source file and line number, which is only possible using the __LINE__ and __FILE__ macros. However, it is pretty unpleasant, inefficient etc... to always have to specify these two parameters.

所以这是我的代码看起来像:

So this is how my code would look like:

namespace Debug {
   void Assert (int condition, std::string message, std::string file, int line);
}

我的问题是,可以放置一个包含这两个参数的宏在 Debug 命名空间内?像这样:

My question is, is it possible to place a macro which includes those two parameters inside the Debug namespace? Like this:

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 ++吗?

Is this valid c++? If not, is there any way of making this work?

推荐答案

#define 是一个预处理器指令。除了除去注释之外,宏之前的 除外(这意味着,在编译之前)。所以在宏被替换时,编译器不知道你的命名空间。

#define is a preprocessor directive. The macros are being replaced before anything else apart from removing comments (which means, before compilation). So at the time macros are replaced, the compiler knows nothing about your namespaces.

像其他人说的,在你的情况下会很好。但是,这是你可以得到的问题:

As other people state, in your case it will be fine. However, This is how you can get problems:

namespace A
{
 void Assert_ (int condition, std::string message, std::string file, int line)
 {
     std::cout << "A";
 }
   #define Assert(a,b) Assert_(a, b, __FILE__, __LINE__)

}
namespace B
{
 void Assert_ (int condition)
 {
     std::cout << "B";
 }
   #define Assert(a,b) Assert_(a)

}

int main(int argc, char *argv[])
{
    A::Assert(0,"asdasd");
    B::Assert(0,"asdasd");
}

所以当它看起来定义是在命名空间 em> ,最后一个 #define 将被使用,在这种情况下会导致编译时错误,因为main将替换为:

So while it looks the defines are "in the namespaces", the are not, and the last #define will be always be used, which in this case will lead to a compile-time error, because the code in main will be replaced by:

A::Assert(0);
B::Assert(0);

而不是

A::Assert(0,"asdasd", _FILE_, _LINE_);
B::Assert(0);

这篇关于是否可以在c ++中的命名空间中放置一个宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆