I'm asking about the best practice widely used in C++ projects. I need to have my own types in the project. It's a collection of couple of typedefs.
Is including header file containing the types good practice in C++ or is it better to use namespaces. If so, why? What are the pros and cons of the two ways?
Right 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:
// ...
};
How would it look like with namespaces?
The two concepts are orthogonal; comparing them the way you ask makes no sense.
Unless you only use these types in a single file, you have to place them in a header so you can easily bring in their definitions when you need them. Then, within that 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 later you can do, for instance, MyNamespace::TInt
rather than int
after you #include "Types.h"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With