1

我有一个设计问题。我想要实现接口的自定义数据类型。例如,使用模板很简单(也许下一个设计不正确——因为我可以做一个通用类而不是下一个——但澄清了我的目标):

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

从前面的类中,很容易得到每个 _data 类成员对应的属性。我的问题:

是否有任何方法(更改设计等)在 IDatatype 和任何类型中实现泛型 setter 和 getter,从而在不使用接口中的模板的情况下操作每个类的 _data 属性?

例如:

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

注意:我的英语不好,对任何错误表示歉意:)

4

1 回答 1

0

您可能可以通过 3 种方式实现这一点,没有一种像使用模板那样优雅且无错误

  1. 将您的数据定义为基类中的 int/float/char 的联合,并从基类的 set/get 方法对该联合进行操作。整个 VB(旧 VB 6)类系统都在这种称为 VARIANT 的数据类型上工作。
  2. 从基类返回 void * 并根据需要进行转换和使用 - 哎呀,祝你好运!!。
  3. 从 getData 返回基本接口引用本身,虽然看起来很有意义,但根本没有任何意义。4.
于 2013-05-06T12:02:11.450 回答