Search code examples
c++templatesruntimetypename

Can I switch an template's parameter type during calling it at runtime in C++?


Firstly, I have a class Manager which could manage diferents primitive data types. For that reason, the Manager has template methods. To call them I have multiple methods with a switch case to select with what type the template method will be called.

I have the next code on C++:

enum MyCallType
{
   MCT_DOUBLE,
   MCT_FLOAT,
   MCT_INT
}

template<class T>
class MyBuffer
{
public:
   MyBuffer (int size, MyCallType type)
   : mData (new T[size]),
   mType (type)
   {}
   ~MyBuffer ()
   {
   delete mData;
   }
   MyCallType getType () { return mType; }

   T* getData(){ return mData; }
private:
   T *mData;
   MyCallType mType;
}


class Manager
{
public:
   Manager (){}
   /* a lot of code */
   void process ()
   {
       switch (mType)
       {
           case MyCallType::MCT_DOUBLE:
           customProcess <double>();
           break;

           case MyCallType::MCT_FLOAT:
           customProcess <float>();
           break;

           / *more cases*/
       }
   }

   template<typename T>
   void customProcess ()
   {
       MyBuffer<T> *myCast = reinterpret_cast <MyBuffer <T> *>(mBuffer);
       T *myData = myCast->getData ();
       /* a lot of process */
   }

private:
   void *mBuffer;
   MyCallType mType;
}

I want to avoid the switch case on "process ()" because I have a lot of function on the manager that work in the same way. Can anybody help me? That I want is possible?


Solution

  • As François said "Template arguments and runtime inputs cannot interact", so change the template's parameters during runtime is not possible, but a good solution could be the use of std::variant or std::any to avoid the switch cases, if you are using C++17 (as Miles said).

    The implementation that I actually use was the use of macros, due I wanted to reduce the code and I'm using C++11