C ++ Compare Template Type At Compile Time

I have a template class. Since templates are processed at compile time, is it possible to compare a template parameter at compile time and use a preprocessor to add specific code? Something like that:

template<class T>
class MyClass
{
   public:
      void do()
      {
         #if T is equal to vector<int>
            // add vector<int> specific code
         #if T is equal to list<double>
            // add list<double> specific code
         #else
            cout << "Unsupported data type" << endl;
         #endif
      }
};

      

How can I compare the types of templates with another type at compile time, as shown in the example above? I don't want to add specific subclasses that handle specific types.

+3


source to share


1 answer


First of all - do

is a keyword, you cannot have a function with that name.
Secondly, the preprocessor works before the compilation stage, so using material from templates in it is out of the question.

Finally, you can only specialize in part of the class template, so to speak. This will work:



#include <iostream>
#include <vector>
#include <list>

template<class T>
class MyClass
{
   public:
      void run()
      {
            std::cout << "Unsupported data type" << std::endl;
      }
};

template<>
void MyClass<std::vector<int>>::run()
{
    // vector specific stuff
}

template<>
void MyClass<std::list<double>>::run()
{
    // list specific stuff
}

      

Demo version.

+9


source







All Articles