我们有一个类层次结构,看起来是这样的:相同的功能,不同的返回类型的类层次
class base
{
};
class derived1 : protected base
{
private:
float m_price;
int m_quantity;
float m_value;
public:
// float calculateValue();
};
class derived2 : protected base
{
private:
double m_price;
long m_quantity;
double m_value;
public:
// double calculateValue();
};
现在我们需要写一个通过价格和数量相乘计算值的函数。目标是尽可能简单地在将来添加新类。正如你可能知道的那样,这不是直接的,因为这些字段的数据类型对于不同的类是不同的。实际上,我们有这些功能在概念上做同样的事情,但在编程方面它们是不同的操作。
为了减少剪切和粘贴所需要的量,我能想到的,到目前为止的解决方案是使用模板函数:
template <class A, B, C>
A calculate_value(B price, C quantity)
{
A result;
// Some code to do the multiplication, not sure if template specialisation is needed
return result;
};
class derived1 : protected base
{
private:
float m_price;
int m_quantity;
float m_value;
public:
float calculateValue()
{
calculate_value < float, float, int > (m_price, m_quantity);
}
};
它的工作不错,但是这将意味着我必须定义每个类中的每个成员函数。例如,如果我想要一个名为getValue的函数,我将需要其他很多这些模板函数。
类定义的类成员的数据类型是已知的,所以不得不将它们放在函数定义中似乎是重复的。有没有可能的方法来避免函数定义中的所有这些模板业务?
谢谢。
安迪
PS我已经看到了以下问题,但这个问题的问题是稍有不同: Returning different data type depending on the data (C++)
我同意usinig浮点数学重复乘法/除法是不是一个好主意。这只是一个说明性的例子。事后看来,我可以选择另一种手术。 – Andy 2009-06-11 15:07:05