We have a class hierarchy which looks something like this:
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();
};
Now we need to write a function which computes the value by multiplying the price and quantity. The aim is to make it as simple as possible to add new classes in the future. As you may be aware, this is not straightforward because the data types of these fields are different for different classes. In effect, we have these functions to do the same thing conceptually, but in programming terms they are different operations.
To minimise the amount of cut and paste required, the solution I can think of so far is to use template functions:
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);
}
};
It does its job all right, but this will mean that I have to define every single member function in each class. For example, I will need another lot of these template functions if I want to have a function called getValue, say.
The data types of the class members are known when the class is defined, so having to put them in the function definitions again seem to be a duplication. Is there a possible way to avoid all this template business in the function definitions?
Thank you.
Andy
PS I have seen the following question, but the issue in that question is slightly different: http://stackoverflow.com/questions/930932/returning-different-data-type-depending-on-the-data-c