c++ - 如何在c ++模板中执行if else依赖类型? [英] how to do an if else depending type of type in c++ template?

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

问题描述

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

    }
};

我知道如何编写模板特化并为 char 类型做一个单独的整个类定义.

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?

如何检查 T 是 int 还是 char?

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

推荐答案

你可以使用 typeid:

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

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

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

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

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

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