mercredi 26 juillet 2017

C++ Alternative to templetized data member

If I have a class DataManager:

class DataManager
{
 public:
   int getRecordInt( size_t i ) const;
   std::string getRecordString( size_t i ) const;

 private:
   std::vector<int> _vInt;
   std::vector<std::string> _vString;
}

I can access records with e.g.

DataManager DM;
// .. populate object ...
int iValue = DM.getRecordInt(3);

In my real application, I will have over a hundred data types (besides int and std::string), so I would like to avoid having to write a separate getter for each of the types.

Now, if C++ would support templatized variable names (which it does not), I could implement the class as:

class DataManager
{
 public:
   template<typename T>
   T getRecord( size_t i ) const
   {
      return _v<T>[i];
   }

 private:
   std::vector<int> _v<int>;
   std::vector<std::string> _v<std::string>;
}

Is there any way I can achieve the purpose in C++?

(Please be aware that although I have simplified the example to the bare minimum, my real-world problem is much more complex and calls for the existence of such DataManager class.)

Aucun commentaire:

Enregistrer un commentaire