如何做一个if依赖类型的类型在c ++模板? [英] how to do an if else depending type of type in c++ template?

查看:104
本文介绍了如何做一个if依赖类型的类型在c ++模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  //模板专业化
#include< iostream>
using namespace std;

//类模板:
template< class T>
class mycontainer {
T元素;
public:
mycontainer(T arg){element = arg;}
T增加(){

//if(T.type==int)/ /如何做这个或类似的东西?
//如果一个int
返回++元素;

//if (T.type==char)
// if((element> ='a')&&(element< ='z'))
// element + ='A' - 'a';
// return element;

}
};



我知道如何写一个模板专门化,并做一个单独的整个类def只是为了char类型。



但是如果我想在一个代码块中处理所有内容呢?



您可以使用 typeid 。 :

  if(typeid(T)== typeid(int))
/ pre>

或者可以使用 std :: is_same 类型特征:

  if(std :: is_same< T,int> :: value)


// template specialization
#include <iostream>
using namespace std;

// class template:
template <class T>
class mycontainer {
    T element;
  public:
    mycontainer (T arg) {element=arg;}
    T increase () {

    //if(T.type==int)//how to do this or something similar?
    //do this if an int
    return ++element;

    //if(T.type==char)
     //if ((element>='a')&&(element<='z'))
      //element+='A'-'a';
      //return element;

    }
};

I know how to write a template specialization and do a separate whole class def just for the char type.

But what if I wanted to handle everything in just one block of code?

How can I check if T is an int or a char?

解决方案

You could use typeid:

if (typeid(T) == typeid(int))

Or you could use the std::is_same type trait:

if (std::is_same<T, int>::value)

这篇关于如何做一个if依赖类型的类型在c ++模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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