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?
The main rule is that you can only forward-declare classes whose memory layout (and thus member functions and data members) do not need to be known in the file you forward-declare it. This would rule out base classes and anything but classes used via references and pointers. Almost.
A forward declaration tells the compiler about the existence of an entity before actually defining the entity. Forward declarations can also be used with other entity in C++, such as functions, variables and user-defined types.
Forward declarations are mainly to avoid circular imports, where one file imports another file which imports the first file etc. Basically when you import a file, contents of the file are substituted at the point of import when you build your project, which is then fed to the compiler.
The Google style guide recommends against using forward declarations, and for good reasons: If someone forward declares something from namespace std, then your code exhibits undefined behavior (but will likely work).
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With