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?
From a dependency point of view, naming all types in a single header is likely to be a maintenance nightmare. It’s understandable for the
typedefbecause you want a unique definition, but there is no reason to forward declare theclasshere.There is no point in forward declaring the
Classsymbol: you pollute your own namespace. Let each file decide independently if they need the symbol or not and forward declare it on their own.It’s not pretty to declare
ClassListeither: it should only be available to those who need it. You could create a specific header for forward declaration ofClassrelated stuff: