Forward declare a standard container?

C++HeaderC++ Standard-Library

C++ Problem Overview


Is it possible to forward declare an standard 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?

C++ Solutions


Solution 1 - C++

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:

http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/5c12858c636ab833/6cd57590509ad6b4">forward declaring std::vector. Works, but is it legal and standard compliant?

Solution 2 - C++

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.

Solution 3 - C++

Apart from what the others said, you may find it useful to know that there is a sanctioned way of forward-declaring iostreams and some related templates: The header <iosfwd>. It would be useful if the standard had more such headers.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobView Question on Stackoverflow
Solution 1 - C++Rob KennedyView Answer on Stackoverflow
Solution 2 - C++Evan TeranView Answer on Stackoverflow
Solution 3 - C++Sebastian MachView Answer on Stackoverflow