0

I known that it is a bad practice using "using namespace xxx" in a header file, But what about the typedef in a interface header file?

for example:

typedef std::set<unsigned int> rsids_type;    //!< typedef something.
struct IRsids 
{
    virtual const rsids_type& GetRsids() = 0;
}

On my option, I think this is also a bad practice for that we import a name "rsids_type" into global namespace? so what about the below action?

struct IRsids 
{
    typedef std::set<unsigned int> rsids_type;    //!< typedef something inside the interface class.
    virtual const rsids_type& GetRsids() = 0;
}
Chen
  • 119
  • 9

1 Answers1

2

Unnecessarily polluting global namespace with typedef is allowed by the language but obviously discouraged by convention.

Namespaces are here (among other things) to avoid names collisions, so put your typedefs within namespaces and/or within classes (as your second example).

typedefs usually go into header files, and are often used as a mean of encapsulation (you hide a complex type behind a simple name), e.g. :

typedef std::vector<std::vector<double>> Matrix

The standard library implementations do it all over the place.

Note:

  • using namespace should be avoided in headers because any include of the header brings the entire namespace with it. This is not the case with a typedef, which is basically a type alias, so there is no problem.
  • In C++11, typedefs and using alias are equivalent:

Example:

using Matrix = std::vector<std::vector<double>>;
Community
  • 1
  • 1
quantdev
  • 23,517
  • 5
  • 55
  • 88