C++在编译期间比较模板类型

goo*_*ons 3 c++ macros templates typename c-preprocessor

我有一个模板类.由于在编译期间处理模板,是否可以在编译期间比较模板参数并使用预处理器添加特定代码?像这样的东西:

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
      }
};
Run Code Online (Sandbox Code Playgroud)

如何在编译期间将模板类型与另一种类型进行比较,如上例所示?我不想添加处理特定类型的特定子类.

jro*_*rok 9

首先do是- 关键字,你不能拥有该名称的功能.
其次,预处理器在编译阶段之前运行,因此使用模板中的东西是不可能的.

最后,您可以只专门化一个类模板的一部分,可以这么说.这将有效:

#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
}
Run Code Online (Sandbox Code Playgroud)

现场演示.

  • @Constructor我们现在可以假设C++ 11是"标准",除非问题明确说明不同的东西. (3认同)