2

I am doing a project which requires me to create arrays of non-homogeneous arrays.

Say the array is "arr".

Then arr[0] might be array of integers, arr[1] might be array of strings, etc.

For that purpose I am using pointers. I have a base class:

 class base_class;

And then I have a template class

template<typename T>     
class temp_class : public base_class{ 
    private:
        T* ptr;
        .....
    public:
        void input(){
        //do something}
};

Now I define the class arr.

class arr{
    private:
        base_class* ptr;
        ....
    public:
        void take_data(){
            temp_class<int>* temp;
            temp = static_cast<temp_class<int>*> (ptr)//OR (ptr+1)
            temp->input();
        }
}

But I get a segmentation fault(or something similar). I guess that the problem is due to the fact that two different types of pointers are pointing to the same object and the "input" function makes sense in only one of them.

How do I fix this? Is there any other way I can implement my idea, without these error prone pointers?

Level 31
  • 403
  • 3
  • 9
  • 2
    Google _c++ discriminated union_ – Barmar Aug 02 '14 at 05:23
  • I'm getting results which relate to unions. Is the "discriminated union" a different form of "union"? – Level 31 Aug 02 '14 at 05:29
  • Yes, it's a union along with a separate field that lets you know the current type of the union value. See my most up-voted answer: http://stackoverflow.com/questions/18577404/how-can-a-mixed-data-type-int-float-char-etc-be-stored-in-an-array/18577481#18577481 – Barmar Aug 02 '14 at 05:32

1 Answers1

1

One option for doing this would be to use an appropriately defined Variant type from the Boost Variant C++ library as your array element.

The Boost documentation for Variant is available at this link

There is a description of how to use a std::vector of Boost Variants in the basic tutorial at that link.

paisanco
  • 4,098
  • 6
  • 27
  • 33