Search code examples
c++classobject

How do you make a class that accepts a type parameter?


I'm creating a C++ class, this class typically deals with numbers. In the example below the class is fixed to an int array. I was hoping to make the data type a bit flexible, of course I can just create a class for each data type but that doesn't feel right. When I want to change something I have to go through all the classes

class SerialArray {
 private:
   unsigned long arrayLength;
 public:
   int * bufferArray;

   SerialArray(unsigned long arraySize){
     arrayLength = arraySize
     bufferArray = new int[arrayLength];
   }
};

I want it to work with at least number related data types such as uint8_t,uint16_t,uint32_t,uint64_t,int,float,signed,unsigned,long,double, and etc.

I know this is possible because I remember vectors having this, for example:

vector<int> myvector(1000);

In fact my class will have similar functionalities as vector. Why not use vector you might ask? I will be using it for an embedded device, which is memory constrained. Instead im creating one where the length is fixed and can do 1 dimension only, basically a glorified array with extra tricks up its sleeve.

Can anyone help me format this class to accept data types as parameters?


Solution

  • you need templates, here a simple templateed version to get you started

    template<typename T>
    class SerialArray {
     private:
       unsigned long arrayLength;
     public:
       T * bufferArray;
    
       SerialArray(unsigned long arraySize){
         arrayLength = arraySize
         bufferArray = new T[arrayLength];
       }
    };
    

    a few comments

    • use size_t for a size
    • use a naming convention for data members , like m_arrayLength or arrayLength_
    • and you could use std::vector