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

前端 未结 5 1043
花落未央
花落未央 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:58

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

    This specific usage would do exactly what you want, but the Assert macro is in no way part of the Debug namespace... it's exactly as if you'd done:

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

    Here, the substitution works not because Assert was in the Debug namespace (it's not in your code or this code, and the preprocessor has no clue what namespaces are about) - it works because Assert is recognised as an identifier for a macro, the substitution of Assert_ is made, then later the compiler proper happens to find there's a Debug::Assert_ So, say you have somewhere later in your translation unit you have some completely unrelated code:

    my_object.Assert(my_functor);
    

    The macro substituion will still kick in to produce a compile-time error saying you have the wrong number of arguments to a macro. Say the unrelated code was instead:

    my_object.Assert(my_functor, "some text");
    

    Then that would be replaced with:

    my_object.Assert_(my_functor, "some text", __FILE__, __LINE__);
    

    (Separately, it's standard practice not to use lower case letters in preprocessor macro names).

提交回复
热议问题