虚拟功能设计问题
virtual function design issue
我有一个基类,其中当前我有一种称为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;
相关文章:
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 询问在设计我的手臂模拟器功能表示格式1
- 需要为 C++ 中的以下问题设计递归算法
- 解析模板的好友功能时出现问题
- creat_list2功能有什么问题?
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 此工厂功能有什么问题?
- 具有sleep_for和sleep_until功能的 gcc 可能存在的问题
- 设计模式,以避免不必要地添加抽象函数以适应新功能
- C++功能设计
- Sinlge 链表,C++,删除所有和搜索功能的问题
- VS2019中内联功能的一些问题
- 模板图的设计问题采用不同的结构
- 桌面计算器出现问题.C++程序设计语言
- 虚拟功能设计问题
- 使用基对象修改/访问派生类的信息的有问题的设计
- 如何为不同的硬件功能设计具有独特实现的过程
- if/else vs虚拟功能:设计性能
- 功能设计决策
- 功能设计