使用场景:
我们在写模板代码时,希望对于某些类型做不同处理,需要对实参类型进行一个判断,std::is_same
是个不错的选择,返回值(::value)为true/false。
实例:
假如,用户用int类型去实例化该模板,我希望做一些特殊操作,代码可以这样写:
#include <iostream>
#include <type_traits>
template <typename T>
void fun(T a){
if(std::is_same<T,int>::value){
std::cout<<"T type is int"<<std::endl;
//we can do something
}else{
std::cout<<"T type is not int"<<std::endl;
//we can do other thing
}
}
调用:
int main(){
fun(100);
fun(2.2);
return 0;
}
结果:
T type is int
T type is not int