Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declare a standard container?

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?

like image 249
Rob Avatar asked Nov 20 '08 23:11

Rob


People also ask

What can be forward declared?

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.

What does forward declaration do?

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.

What is forward declaration in Objective C?

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.

Is forward declaration good practice?

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).


2 Answers

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.

like image 34
Evan Teran Avatar answered Sep 23 '22 01:09

Evan Teran


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?

like image 73
Rob Kennedy Avatar answered Sep 20 '22 01:09

Rob Kennedy