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
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
