我们有一个类层次结构,看起来像这样:
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 based on the data (C++)