Reputation: 2719
Consider one has some user defined types, and containers of those types that are often manipulated because there are often multiple instances of those types on screen at a time.
Currently I have a header with an associated source file and a namespace to hold these containers, but should I create a separate class to hold them? Should I put the containers in the same header file as the class that they contain (but obviously outside the class)? What is the standard practice for situations like this?
Upvotes: 1
Views: 137
Reputation: 65649
I once typedef'd them whenever a specific class has the container as part of that class's interface. Then anyone who needed to use that class easily figured out that a "FooVec" is a std::vector of Foo without a lot of fus.
However, this is an imperfect solution, consider the following code:
namespace bar
{
typedef std::vector<Foo> FooVec;
class CClass
{
CClass(FooVec&)
{
...
}
};
}
Naturally the problem comes in when your colleague redefines FooVec for their class:
namespace bar
{
typedef std::vector<const Foo> FooVec;
class CAnotherClass
{
CAnotherClass(FooVec&)
{
...
}
}
};
The simplest thing I've found to solve this is to have them in roughly one common include per namespace/library/group of associated classes. So when someone else adds a typedef to something in the bar namespace, you can have them all in one place. IE:
barTypes.h
namespace bar
{
typedef std::vector<Foo> FooVec;
typedef std::vector<const Foo> FooConstVec;
}
By keeping it to one header per small set of classes (ie per namespace) you don't get a gigantic file full of typedefs. It still gives your users good visibility into the types that are a part of your class's interface. Once this header is established, its just a matter of maintaining discipline on your team to use it instead of establishing additional typedefs.
May also wish to have this header as part of a precompiled header if you're anal about build performance.
Upvotes: 2