【问题标题】:C++ Compare template type during compile timeC++ 在编译时比较模板类型
【发布时间】:2014-12-09 03:59:02
【问题描述】:

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

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
      }
};

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

【问题讨论】:

标签: c++ templates macros c-preprocessor typename


【解决方案1】:

首要任务 - 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
}

Live demo.

【讨论】:

  • 啊,不知道你只能专门化一个特定的功能。似乎预处理器的想法行不通,所以我会采用您的解决方案 - 看起来很干净。
  • 显式特化的定义应该放在源文件中...并且 &gt;&gt; 右尖括号样式仅在 C++11+ 中受支持。
  • @Constructor 我们现在可以假设 C++11 是“标准”,除非问题明确说明了一些不同的东西。
猜你喜欢
  • 1970-01-01
  • 2014-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多