how to do an if else depending type of type in c++ template?(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依赖类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++ - 如何在c ++模板中执行if else依赖类型?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
