Namespaces and Headers

I ask about the best practices widely used in C ++ projects. I need to have my own types in the project. This is a collection of several typedefs.

Includes a header file containing C ++ best practice types, or better to use namespaces. If so, why? What are the pros and cons of the two ways?

Now it looks like this:

types.h:

#ifndef TYPES_H #define TYPES_H #include <list> // forward declaration class Class; typedef int TInt; // ... typedef std::list<Class> class_list; #endif 

class.h:

 #ifndef CLASS_H #define CLASS_H #include "types.h" class Class { public: // ... TInt getMethod(); private: // ... }; 

What does it look like with a namespace?

+4
source share
3 answers

In terms of dependency, names of all types in one header are likely to be a service nightmare. This is understandable for typedef because you want a unique definition, but there is no reason to forward the class declaration here.

 // types.h namespace myproject { typedef int TInt; } // namespace myproject 

There is no point in striking to declare a class symbol: you are polluting your own namespace. Let each file independently determine whether it needs a symbol or not, and the redirection declares it on its own.

It is not so simple to declare a ClassList : it should be available only to those who need it. You can create a specific header for directly declaring a class related things:

 // class_fwd.h namespace myproject { class Class; typedef std::list<Class> ClassList; } // namespace myproject // class.h #include "myproject/class_fwd.h" namespace myproject { class Class {}; } // namespace myproject 
+4
source

Two concepts are orthogonal; comparing them as you ask does not make sense.

If you are not using only these types in a single file, you should put them in the header so that you can easily enter your definitions when you need them. Then in this header you can include your namespace:

 #ifndef TYPES_H #define TYPES_H #include <list> namespace MyNamespace { // forward declaration class Class; typedef int TInt; // ... typedef std::list<Class> class_list; } #endif 

Then you can do, for example, MyNamespace::TInt , and not int after #include "Types.h"

+10
source

Erm ... I think including the header file is fine. I'm not sure how namespaces attack the same problem at all ...

Most importantly, with any โ€œbest practiceโ€ like this, BE ACCORDING TO.

+1
source

Source: https://habr.com/ru/post/1307423/


All Articles