C ++在编译时比较模板类型 [英] C++ Compare template type during compile time

查看:73
本文介绍了C ++在编译时比较模板类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

首先,-do是关键字,您不能使用具有该名称的函数.
其次,预处理器在编译阶段之前运行,因此无法使用其中的模板内容.

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
}

实时演示.

这篇关于C ++在编译时比较模板类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆