tags:

views:

643

answers:

3

Is it possible to forward declare an STL container in a header file? For example, take the following code:

#include <vector>

class Foo
{
private:
    std::vector<int> container_;
    ...
};

I want to be able to do something like this:

namespace std
{
    template <typename T> class vector;
}

class Foo
{
private:
    std::vector<int> container_;
    ...
};

Can this be done?

+6  A: 

I don't think so because the compiler would have no way of knowing how much space to allocate for the container_ object. At best you could do:

std::vector<int> *container_;

and new it in the constructor, since the compiler knows the size of a pointer.

Evan Teran
exactly what I just wanted to say
badbadboy
+4  A: 

Declaring vector in the std namespace is undefined behavior. So, your code might work, but it also might not, and the compiler is under no obligation to tell you when your attempt won't work. That's a gamble, and I don't know that avoiding the inclusion of a standard C++ header is worth that.

See the following comp.std.c++.moderated discussion:

forward declaring std::vector. Works, but is it legal and standard compliant?

Rob Kennedy
I followed your link to the discussion, but the people do not seem to be coming to an conclusion. Apparently, the stl implementation must not add any template parameters to the standard containers. hence, it should be allowed to forward declare the template.
Haplo
It's undefined, @Haplo. If the implementation *you're* using chooses to define the behavior beyond what the standard says, that's great, but it's still undefined, so your code won't be portable. The conclusion (judging from statements left unchallenged) is that the standard should allow it, but doesn't, and that there are two workarounds: Wrap the standard types in forward-declared user structs, or just bite the bullet and include the standard header. The latter is easy to do.
Rob Kennedy
A: 

Apart from what the others said (except Adam Rosenfield), you may find it useful to know that there is a sanctioned way of forward-declaring iostreams and some related templates: http://msdn.microsoft.com/en-us/library/1af12yty%28VS.80%29.aspx . It would be cool if the standard had more such headers.

phresnel