3

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
goocreations
  • 2,938
  • 8
  • 37
  • 59
  • 1
    possible duplicate of [Use a template parameter in a preprocessor directive?](http://stackoverflow.com/questions/2904376/use-a-template-parameter-in-a-preprocessor-directive) – Michal Hosala Oct 14 '14 at 11:15

1 Answers1

9

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.

jrok
  • 54,456
  • 9
  • 109
  • 141
  • Ahh, didn't know you could specialize only a specific function. Seems like the preprocessor idea won't work, so I'll go with your solution - seems clean. – goocreations Oct 14 '14 at 11:24
  • Definitions of explicit specializations should be placed in a source file... And `>>` style of closing angle brackets is supported only in C++11+. – Constructor Oct 14 '14 at 11:25
  • 3
    @Constructor We can assume C++11 to be "the" standard now unless the question explicitly states something different. – leemes Oct 14 '14 at 11:35