I'm trying to get a good structure in some code I'm writing but I'm not quite sure about header files. One of the problems I have is: I know I'm not supposed to include namespaces in header files but I don't know where else to put it.
Consider this header:
// deck.h
#pragma once
#include <vector>
#include "card.h"
using namespace std;
typedef vector<card> pile;
class deck{
public:
deck();
~deck();
void shuffle();
card takeCard();
int getSize();
private:
pile cDeck;
};
The code in card.h is the definition of a card struct. Should the typedef even be in the header file? And ifso, how do I avoid using std::vector?
Any tips would be appriciated.
3 Answers 3
You don't put it at all. Use std::vector
instead of vector
, there are only 5 additional characters to type. The typedef
is OK to be in header files.
As you probably are aware, using namespace std;
in a header is BAD. Why? Because all files that will include your header will automatically use namespace std;
, and it's relatively easy to get into conflicting names, especially in large projects where the client may not be aware of the using
directive he/she is implicitly using.
Alternatively, you may use namespace std;
inside an inline function definition in the header,
inline void f()
{
using namespace std;
cout << "bla" << endl;
}
or classes,
class Foo
{
using namespace std;
// rest
};
This way, the using
is effectively "seen" only in its enclosing scope.
Related: What's the scope of the "using" declaration in C++?
4 Comments
use namespace std;
in a scope, so it won't "leak" outside of it.std::
every time. It's really a normal thing to do. The only time I use a namespace directive is with long nested namespaces, like boost::gregorian
. Even then, I don't completely remove it, I just come up with an abbreviation for it (e.g. namespace dt = boost::gregorian;
), and only in the scope of a function.Removing the using directive is trivial, just rewrite the code to
// deck.h
#pragma once
#include <vector>
#include "card.h"
typedef std::vector<card> pile;
class deck{
public:
deck();
~deck();
void shuffle();
card takeCard();
int getSize();
private:
pile cDeck;
};
Comments
Using and using namespace can be used within functions within your implementation. If you want to limit possible conflicts as mentioned above, and you are in a situation where you really need to use "using" or "using namespace", keep it within small functions.
using namespace std;
in a header file is a pretty bad idea!#include <vector>
orstd::vector
, you need only avoidusing namespace std;
. (Also, if thepile
type is internal to the class, which seems like a good idea, the typedef should be in the private section of the class.)using std::vector
is a super better option here!