Is it possible to place a macro in a namespace in c++?

前端 未结 5 1056
花落未央
花落未央 2020-12-05 09:55

My application uses another output than the standard output for logging information, which is why I wrote my own Log(), Error(), Panic()

5条回答
  •  醉话见心
    2020-12-05 10:33

    #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");
    }
    

    So while it looks like the defines are "in the namespaces", they 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);
    

    instead of

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

提交回复
热议问题