Search code examples
c++variable-types

How to initialize a class that manages a buffer whose data type is passed at instantiation.


I need to create a Buffer class whose type of variables that constitute the managed buffer is decided at istantiation time. Thus, I need a buffer class of long int bytes, 30 elements long, I will instantiate something like:

GeneralBuffer myLongBuffer(long int, 30); or GeneralBuffer myLongBuffer(LONG, 30);

While if I need a unsigend floating type:

GeneralBuffer myFloatingBuffer(unsigend float, 30); or or GeneralBuffer myLongBuffer(UFLOATING, 30);

Any suggestions?


Solution

  • Since types are a compile-time construct, you can't pass them as arguments to a function. Instead you want templates. Templates allow to instantiate different implementations of a class or function depending on the template type parameters you pass to it. So if you have:

    template <typename T>
    class GeneralBuffer
    {
      private:
        T* internal_buffer;
      public:
        GeneralBuffer(size_t size);
    };
    

    You can instantiate GeneralBuffer for int and create an object of that type like so:

    GeneralBuffer<int> my_int_buffer(30);
    

    However, this just looks like a reimplementation of std::vector.

    Alternatively, if the size of the buffer is also a compile-time constant, you could also pass it as a template parameter:

    template <typename T, std::size_t N>
    class GeneralBuffer
    {
      private:
        T internal_array[N];
      public:
        GeneralBuffer();
    };
    

    Which you would use like so:

    GeneralBuffer<int, 30> my_int_buffer;
    

    However, this just looks like a reimplementation of std::array.