虚拟功能设计问题

virtual function design issue

本文关键字:问题 功能设计 虚拟      更新时间:2023-10-16

我有一个基类,其中当前我有一种称为get_value()的方法,该方法应返回值适当地转换为各种原始数据类型的值。由于,我们不能使用仅返回类型有所不同的虚拟方法,因此我必须执行以下操作:

virtual void get_value(unsigned int index, unsigned char & r) const = 0;
virtual void get_value(unsigned int index, char & r) const = 0;
virtual void get_value(unsigned int index, unsigned short & r) const = 0;
virtual void get_value(unsigned int index, short & r) const = 0;
virtual void get_value(unsigned int index, unsigned int & r) const = 0;
virtual void get_value(unsigned int index, int & r) const = 0;
virtual void get_value(unsigned int index, float & r) const = 0;
virtual void get_value(unsigned int index, double & r) const = 0;

从维护的角度来看,这很烦人,并且用户必须做类似:

的用法也有些尴尬。
unsigned char v;
obj->get_value(100, v);

无论如何,所有这些类型的儿童课都必须覆盖所有孩子的事实令人讨厌。我想知道是否有人有任何建议来避免这种情况,或者以某种方式使用一个虚拟函数以更紧凑的方式做到这一点。

儿童课可能是:

void get_value(unsigned int index, unsigned char & r) const {get<unsigned char>(index, r);}
void get_value(unsigned int index, char & r) const {get<char>(index, r);}
void get_value(unsigned int index, unsigned short & r) const {get<unsigned short>(index, r);}
void get_value(unsigned int index, short & r) const {get<short>(index, r);}
void get_value(unsigned int index, unsigned int & r) const {get<unsigned int>(index,r);}
void get_value(unsigned int index, int & r) const {get<int>(index,r);}
void get_value(unsigned int index, float & r) const {get<float>(index,r);}
void get_value(unsigned int index, double & r) const {get<double>(index,r);}

这个专业模板获得的方法对每个孩子类都有特定的方法。

您应该考虑仅创建不同的功能。

int getInt();
double getDouble();

等等。

看来您的调用代码必须知道任何情况下的区别。由于您可以执行的操作没有真正的抽象(显然,至少),因此您也可以清楚地表明。模板和面向对象的类可能只会增加不必要的复杂性。

当然,为了判断这一点,可能需要更多的上下文。只是我的0.02€:)

您可能需要查看模板。他们将允许您指定类型:

foo<float>(bar); // calls the float version
foo<int>(bar); // calls the int version

您可以拥有一个单个虚拟函数调用,该调用像这样返回 boost::variant

using vartype = boost::variant<
    unsigned char,
    char,
    unsigned short,
    short,
    // ...
>;
virtual vartype get_value(unsigned int index) const = 0;