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?
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?
There are several ways to use stuff from other namespaces without having to repeat the namespace on every instance.
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.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.namespace co = cocos2d;
Now you can refer to members of the cocos2d
namespace as if they were members of the co
namespace.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.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