C++ Compare template type during compile time

孤者浪人 提交于 2019-12-22 10:51:03

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/26359438/c-compare-template-type-during-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!