tags:

views:

56

answers:

1

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?

+2  A: 

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.

Doug T.
The second part you said is essentially what I did. Thanks for the info. One other unrelated question, global constants vs class variables (invariants)? I'm assuming class variables are preferred, but am I right in this assumption?
trikker
Its preferred (by me) to limit the value to the lowest needed scope. IE if its used only in a function, just that function. If its used throughout a class, just define it for that class. Etc...
Doug T.