Search code examples
c++templatesmacrosc-preprocessortypename

C++ Compare template type during compile time


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

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 template types to another type during compile time as shown in the example above? I do not want to add specific subclasses that handle specific types.


Solution

  • First things first - do is a keyword, you can't have a function with that name.
    Secondly, preprocessor runs before the compilation phase, so using stuff from templates in it is out of the question.

    Finally, you can specialize only a part of a 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
    }
    

    Live demo.