开发者

C++ namespace help

If I have multiple class and I want to have them all come under the same namespace and in my project I just want to have one include and that will give me all of the classes how would I go about doing this? I have played around with this but keep hi开发者_JS百科tting a dead end.

Thanks in advance.


If you want only one include, namespaces have nothing to do with this.

You can create a file that only contains #include statements.

Something like this:

//classes file
#include "classA"
#include "classB"
#include "classC"

And the include all of them with only one include

#include "classes"

A real example can be found in the STL.

Take vector for instance:

#ifndef _GLIBCXX_VECTOR
#define _GLIBCXX_VECTOR 1

#pragma GCC system_header

#include <bits/stl_algobase.h>
#include <bits/allocator.h>
#include <bits/stl_construct.h>
#include <bits/stl_uninitialized.h>
#include <bits/stl_vector.h>
#include <bits/stl_bvector.h> 

#ifndef _GLIBCXX_EXPORT_TEMPLATE
# include <bits/vector.tcc>
#endif

#ifdef _GLIBCXX_DEBUG
# include <debug/vector>                                                        
#endif

#endif /* _GLIBCXX_VECTOR */

You get all of this by just doing #include <vector>


Namespaces and header files are unrelated. If you want to provide a single header file for inclusion you can either go with Tom's advice of adding a 'include-all' header or you can pack all your headers into a single file (this might be a bad idea unless the codebase is really stable, as a change in a single element will force recompiling everything). Anyway you can use different namespaces within the same header:

#ifndef HEADER_GUARD_H_
#define HEADER_GUARD_H_
namespace A {
   class TheA {};
}
namespace B {
   class TheB {};
}
namespace A {  // you can even reopen the namespace
   class AnotherA {};
}
#endif

Note that the difference is the packaging: whether you need to ship one or more files... in Tom's answer the preprocessor will generate a file similar to the manually generated header before passing the contents to the compiler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜