3

I use cocos2dx. When I use classes from it I need to type cocos2d:: very often unless I type using namespace cocos2d;.

How can I avoid having to repeat the namespace all the time?

Chris
  • 6,914
  • 5
  • 54
  • 80
vito_yu
  • 63
  • 5

2 Answers2

7

There are several ways to use stuff from other namespaces without having to repeat the namespace on every instance.

  • Import the entire namespace: using namespace cocos2d; You can now use all members of that namespace by only their name without the namespace prefix. This pollutes your own namespace with possibly quite a few names (depending on the contents of the imported namespace) which might not be desirable.
  • Import single names from that namespace: using cocos2d::MyClassName; This only imports the given name. The upside is that your namespace is not polluted. The downside is that you will have to do it for every namespace member you want to import. If you only need a few then this approach is fine.
  • Create a namespace alias: namespace co = cocos2d; Now you can refer to members of the cocos2d namespace as if they were members of the co namespace.
  • Create a type alias (since C++11): using CoClass = cocos2d::MyClassName; You can then refer to the aliased member with the identifier you chose. This can be especially helpful when an imported type shadows a type in your own namespace.
Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
Chris
  • 6,914
  • 5
  • 54
  • 80
3

Chris's answer is correct and complete, but I would add that it's a better idea to explicitly specify every member's namespace to avoid ambiguity in other files that included your header file.

using namespace cocos2d; will implicitly use that namespace in every file that includes your header. You may put it inside the .cpp file. Same thing goes for using cocos2d::MyClassName; and namespace aliases.

Those will all work, but you shouldn't use them.

See that answer to the question: “using namespace” in c++ headers

Community
  • 1
  • 1
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129