mardi 8 septembre 2020

C++ Template-based Design - What is the best template guidelines when structuring a template-based project? (in terms of casting types effectively)

Assume the following structure of templated C++ code:

class SpokenLang
{
    private: std::string lang;
    ...
};

class Greek : public SpokenLang
{
    ...
};
class English : public SpokenLang
{
    ...
};

// HDT (stands for Height Data Type and is the data type used to specify the selected HT)
template <typename HDT> // For example we could use either float or double for the Height Data Type
class AbsoluteHeight
{
    private: HDT height;
    ...
};


// HDT (stands for Height Data Type and is the data type used to specify the selected HT)
template <typename HDT> // For example we could use either float or double for the Height Data Type
class RelativeHeight
{
    private: HDT height;
    ...
};

// SL (stands for SpokenLanguage derived classes
// HT (stands for Height Type - either AbsoluteHeight or RelativeHeight)
// HDT (stands for Height Data Type and is the data type used to specify the selected HT)
template <typename SL, typename HT, typename HDT>
class Student
{
    private: SL spokenLanguage;
             HT<HDT> height;
    ...
}

Now assume that you have an array of Students. What is the best Template design in order to facilitate a simple and clear design without having to specify the exact types used for each Student object?

For example: Should i use pointers and static cast them at runtime in order to guess the appropriate types used for each Student?

Student** students = new Student*[10];
students[0] = new Student<Greek,AbsoluteHeight,float>();
students[1] = new Student<English,RelativeHeight,float>();
...

OR use the following more compact design (more compact in terms of the number of template parameters usages?:

// ...(declarations omitted for brevity)...

// SL (stands for SpokenLanguage derived classes
// HT (stands for Height Type - for example AbsoluteHeight<float> or RelativeHeight<double>)
template <typename SL, typename HT>
class Student
{
    private: SL spokenLanguage;
             HT height;
    ...
};
...
Student** students = new Student*[10];
students[0] = new Student<Greek,AbsoluteHeight<float>>();
students[1] = new Student<English,RelativeHeight<double>>();
...

How can i safely cast the "missing" info about a nested template parameter when i need to manipulate a student object? My questions are:

  • "What is the best template guidelines when structuring a template-based project?"
  • Are there any guidelines in order to keep my templatized classes from being "bloated" with many template parameters?
  • Are there any books talking about such template guidelines (tips/best practices)? Can you name any of them (or the best one) please?

Aucun commentaire:

Enregistrer un commentaire