简体   繁体   中英

C++ macros and namespaces

I've got a problem with using macros in namespaces. The code is

#include <iostream>

namespace a
{
#define MESSAGE_A(message) \
    std::cout << (message) << std::endl;
}

#define MESSAGE_A(message) \
    std::cout << (message) << std::endl;

int main()
{
    //works fine
    MESSAGE_A("Test");
    //invalid
    a::MESSAGE_A("Test")
    return 0;
}

What's the proper variant of using namespaced objects in macros.

Macros are handled by the pre-processor, which knows nothing about namespaces. So macros aren't namespaced, they are just text substitution. The use of macros really is discouraged, among other reasons because they always pollute the global namespace.

If you need to print out a message, and you need it to be namespaced, simply use an inline function. The code seems simple enough to be properly inlined:

namespace a
{
  inline void MESSAGE_A(const char* message) 
  {
    std::cout << message << std::endl;
  }
}

It will not work. Macroses knows nothing about namespaces. If you want to use namespaces - you must not use macroses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM