Search code examples
c++classc++11standard-library

Class that contains a list of itself


This is what I am trying to do (in my header file):

#include <forward_list>

class Data {
public:
        Data(int type, union data value);
        int which_type();
        void set_int(const int& i);
        void set_list(std::forward_list<Data*>& l);
        int get_int();
        std::forward_list<Data*>* get_list();
private:
        union data actual_data;
        int type;
};

union data {
        int i;
        std::forward_list<Data*> l;
};

If everything were to work properly, this would create a class which could contain an integer or a list, and it would be as type-safe as possible because I would call the which_type function before every call to one of the get functions, and the get functions would throw an exception if the object isn't the correct type.

However, this isn't possible because Data needs a union data, and union data needs a forward_list<Data*>. I believe boost has what I am looking for, but is there a way to do this without boost? I would just rather use the standard library in order to learn more about the c++ standard library.


Solution

  • All you need is to forward declare the class Data and then declare the union data before the class Data proper declaration.

    #include <forward_list>
    
    
    class Data;
    union data {
            int i;
            std::forward_list<Data*> l;
    };
    
    
    class Data {
    public:
            Data(int type, union data value);
            int which_type();
            void set_int(const int& i);
            void set_list(std::forward_list<Data*>& l);
            int get_int();
            std::forward_list<Data*>* get_list();
    private:
            union data actual_data;
            int type;
    };
    

    Compiles with g++ and clang++ with no problem.