I am trying to create a struct that includes a vector with type being that same struct. However, when I build, errors that indicate I am missing a ';' before '>' appear. I am not sure if the compiler is even recognizing that the vector as a thing :/ and I have already included in my code. Here is what I have so far:
#include <vector>
typedef struct tnode
{
int data;
vector<tnode> children;
GLfloat x; //x coordinate of node
GLfloat y; //y coordinate of node
} tnode;
Any help would be greatly appreciated!!
Your code is invoking undefined behavior because standard containers such as vector
cannot contain incomplete types, and tnode
is an incomplete type within the struct definition. According to the C++11 standard, 17.6.4.8p2:
the effects are undefined in the following cases: [...] if an incomplete type (3.9) is used as a template argument when instantiating a template component, unless specifically allowed for that component.
The Boost.Container library provides alternative containers (including vector
) which can contain incomplete types. Recursive data types such as the one you want are given as a use case of this.
The following would work with Boost.Container:
#include <boost/container/vector.hpp>
struct tnode
{
int data;
//tnode is an incomplete type here, but that's allowed with Boost.Container
boost::container::vector<tnode> children;
GLfloat x; //x coordinate of node
GLfloat y; //y coordinate of node
};
What you have is not standards compliant (thanks to @jonathanwakely for confirming that). So it is undefined behaviour, even if it compiles on some popular platforms.
The boost container library has some standard library-like containers that do support this, so you could in principle modify your struct to use one of these:
#include <boost/container/vector.hpp>
struct tnode
{
int data;
boost::container::vector<tnode> children;
GLfloat x; //x coordinate of node
GLfloat y; //y coordinate of node
};
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