1

I am trying to store some data that I read from a file. The data is an array and can be one of a few types; short, float, etc. I am trying to abstract this data to a class, so I immediately thought:

class BaseData {
public:
    void *data;
    virtual void foo() = 0;
};

template <typename T>
class Data : public BaseData {
public:
    T *data;

    Data(const File *file) {
        data = (T*) file->data;
    }

    T operator()(int x, int y, int z) {
       return data[x + y*yd + z*zd];
    }

    void foo() {}
};

I use a switch statement when reading the file to instantiate the right object and then when I want to work with the different Data objects I do:

if (Data<short> *d = dynamic_cast<Data<short> *>(image->data)) {
   cout << (*d)(100, 50, 100) << endl;
}

where image->data is of type BaseData.

What are your thoughts on this? Is this the right way to go about things? Ideally I would like to grab the array (and the type) and do things with it, but I don't know what the type is going to be at compile time.

2
  • 1
    Just a quick point, by declaring T *data in class Data, you're hiding void *data defined in class BaseData - the void pointer will never be used. Commented Jul 12, 2013 at 21:26
  • I would recommend boost::variant. It allows you to make type safe unions. Commented Jul 12, 2013 at 21:34

1 Answer 1

1

What are your thoughts on this? Is this the right way to go about things? Ideally I would like to grab the array (and the type) and do things with it, but I don't know what the type is going to be at compile time.

Yes, generally speaking creating a parametric polymorphic wrapper like you are doing is a good approach. It is similar to the "Any" design pattern as exemplified by boost::any, and attaches run-time type information to otherwise unrelated non-polymorphic types such as int, float, etc.

You should also look at boost::variant which is a similar but slightly different approach. In variant the set of types become template parameters of the Base. As a pro this allows some additional compile-time checking and also a slightly more efficient implementation, as a con it has an arguably more complicated interface.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.