// 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依赖类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
为什么两个函数的地址相同?Why do two functions have the same address?(为什么两个函数的地址相同?)
为什么 std::function 的初始化程序必须是可复制构Why the initializer of std::function has to be CopyConstructible?(为什么 std::function 的初始化程序必须是可复制构造的?)
混合模板与多态性mixing templates with polymorphism(混合模板与多态性)
我什么时候应该使用关键字“typename"?使用模When should I use the keyword quot;typenamequot; when using templates(我什么时候应该使用关键字“typename?使用模板时)
依赖名称解析命名空间 std/标准库Dependent name resolution amp; namespace std / Standard Library(依赖名称解析命名空间 std/标准库)
gcc 可以编译可变参数模板,而 clang 不能gcc can compile a variadic template while clang cannot(gcc 可以编译可变参数模板,而 clang 不能)