views:

215

answers:

3

Hi,

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?

+1  A: 

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

The main thing with any "best practice" like this is BE CONSISTENT.

Goz
+9  A: 

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"

Dennis Zickefoose
+4  A: 

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 typedef because you want a unique definition, but there is no reason to forward declare the class here.

// types.h

namespace myproject
{
  typedef int TInt;
} // namespace myproject

There is no point in forward declaring the Class symbol: 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 ClassList either: it should only be available to those who need it. You could create a specific header for forward declaration of Class related stuff:

// 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
Matthieu M.