1

I have a design question. I want custom datatypes implementing an interface. For example, using templates is simply (maybe next design isn't correct -because I can do a generic class instead of the next- but clarifies my goal):

template <typename T>
class IDatatype
{
public:
    virtual T getData() const = 0;
    virtual void setData(T pData) = 0;
};

class MyChar: public IDatatype<char>
{
public:
    void setData(char pData){...}
    char getData() const{...}

private:
    char _data;
};

class MyInt: public IDatatype<int>
{
public:
    void setData(int pData){...}
    int getData() const{...}

private:
    int _data;
};

IDatatype<int> *data = new MyInt(); // parametrized interface, bad idea :(
data->getData(); // it works ok

From previous classes, it is easy to get the attribute corresponding to each _data class member. My question:

Is there any way (change design, etc.) to implement generic setter and getter in IDatatype and for any type and thus manipulate the _data attribute of each class without using templates in the interface?

For example:

class IDatatype
{
public:
    // pure virtual getters and setters for specialized _data fields. Here is my design question.
};

class MyChar: public IDatatype
{
public:
    void setData(char pData){...};
    char getData(){...};

private:
    char _data;
};

class MyInt: public IDatatype
{
public:
    void setData(int pData){...};
    int getData(){...};

private:
    int _data;
};

IDatatype *intData = new MyInt(); // no parametrized interface!
intData->getData(); // how can I create this method from IDatatype?

IDatatype *charData = new MyChar();
charData->getData(); // the same here

NOTE: I have no good english, apologize for any errors :)

Chu
  • 468
  • 1
  • 5
  • 21
  • C++ is not right language for do such things. You cannot do this automatically, only manually, by saving type-identification in object, by creating visitor may be, by store void* (boost::any, boost::variant) as field, etc... – ForEveR May 06 '13 at 05:46
  • See this [answer](http://stackoverflow.com/a/4233138/1930331). @ForEveR says a lot of what is there. – isaach1000 May 06 '13 at 05:57

1 Answers1

0

You could probably achieve this in 3 ways, none as elegant and error free as using a template

  1. Define your data as a union of int/float/char in the base class and act on this union from the set/get methods of the base class. The entire VB (old VB 6) class system works on such a data type called VARIANT.
  2. Return void * from base class and cast and use as appropriate - yuck & good luck!!.
  3. Return the base interface reference itself from the getData which though appearing to be meaningful, has no meaning at all. 4.
computinglife
  • 4,321
  • 1
  • 21
  • 18