C++ multiple type array

An array is a systematic arrangement of objects (of the same size). In C/C++ you can't create an array of variable size elements.

However, you can use polymorphism to active this.

Create an array of abstract type pointer and cast an array element based on its type.

Example:

namespace Array {
    enum Type  {
        Type1T,
        Type2T,
    };

    class AbstractType {
        public:
            virtual Type GetType() = 0;
            virtual ~AbstractType() {} 
    };

    class Type1 : public AbstractType  {
        public:
            Type GetType() { return Type1T;}

            int a;
            string b;
            double c;
    }; 

    class Type2 : public AbstractType  {
        public:
            Type GetType() { return Type2T;}

            int a;
            string b;
            string c;
            double d; // whatever you want
    };
}

And create your array of multiple different types as;

vector<Array::AbstractType*>  my_array;

A vector in c++ will have all of its elements with the same type. An alternative is to have a vector of vectors, but again, the elements of the inner vectors will have to be of the same type.

Probably the problem you try to solve will have a better solution than what you try to achieve. There is an ugly and definitely not advisable solution - to use vector<vector<void*> > but this is both dangerous and unmaintainable.

If you will only have elements of a given set of types, then create an abstract type that has an implementation for all there types. For instance, define MyType and inherit it in MyTypeInt, MyTypeDouble and MyTypeString. Then declare a vector<vector<MyType*> >, for instance, (even better would be to use a scoped_array or something of the sort instead of the inner vector).

EDIT: as per nijansen comment, if boost is available you can create a vector of vectors of Boost.Variant.

Tags:

C++

Arrays