相同的函数,类层次结构的不同返回类型

And*_*ndy 0 c++ templates overriding function

我们有一个类层次结构,看起来像这样:

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();
};
Run Code Online (Sandbox Code Playgroud)

现在我们需要编写一个函数,通过乘以价格和数量来计算价值.目的是尽可能简单地在将来添加新类.您可能知道,这并不简单,因为这些字段的数据类型对于不同的类是不同的.实际上,我们有这些函数在概念上做同样的事情,但在编程术语中它们是不同的操作.

为了最大限度地减少所需的剪切和粘贴量,我能想到的解决方案是使用模板函数:

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);
    }
};
Run Code Online (Sandbox Code Playgroud)

它可以完成任务,但这意味着我必须在每个类中定义每个成员函数.例如,如果我想要一个名为getValue的函数,我将需要另外很多这些模板函数.

在定义类时,类成员的数据类型是已知的,因此必须将它们再次放入函数定义中似乎是重复的.有没有办法在函数定义中避免所有这些模板业务?

谢谢.

安迪

PS我看到了以下问题,但该问题的问题略有不同: 根据数据返回不同的数据类型(C++)

Har*_*lby 6

虽然我不能说我喜欢使用返回不同类型的函数的多个派生类的想法,但有一种方法可以做到这一点.

template
class base<typename value_type>
{
public:
    value_type calculateValue();
};
class derived1 : protected base<float>
{
private:
    float m_price;
    int m_quantity;
    float m_value;
};
class derived2 : protected base<double>
{
private:
    double m_price;
    long m_quantity;
    double m_value;
};
Run Code Online (Sandbox Code Playgroud)

这允许您改变派生类中的value_type,但是在基础中声明所有常用函数(就像您应该这样做).这类似于STL中用于地图等的方法.