当前位置:网站首页>Judge whether the two types are the same
Judge whether the two types are the same
2022-07-23 09:28:00 【Hair like snow ty】
There is one in the standard library std::is_same Class template for , Used to judge whether the two types are the same , Take a look at the following test first :
int main()
{
cout << std::is_same<int, int>::value << endl;
cout << std::is_same<int, double>::value << endl;
cout << std::is_same<int, const int>::value << endl;
system("pause");
return 0;
}
result ;
How to realize one by yourself ?
template<typename T1, typename T2>
struct IsSameType
{
static const int value = 0;
};
template<typename T1>
struct IsSameType<T1,T1>
{
static const int value = 1;
};
int main()
{
cout << IsSameType<int, int>::value << endl;
cout << IsSameType<int, double>::value << endl;
cout << IsSameType<int, const int>::value << endl;
system("pause");
return 0;
}
result :
You can use a variable template to make an improvement .
Be careful : Cannot use alias template , Because the result is a value , Not a type .
template<typename T1,typename T2>
const int IsSame_v = IsSameType<T1, T2>::value;
int main()
{
cout << IsSame_v<int, int> << endl;
cout << IsSame_v<int, double><< endl;
cout << IsSame_v<int, const int><< endl;
system("pause");
return 0;
}
result :
In fact, you can also optimize class templates , as follows :
template<typename T1, typename T2>
struct IsSameType:false_type
{
};
template<typename T1>
struct IsSameType<T1,T1>:true_type
{
};
template<typename T1,typename T2>
const int IsSame_v = IsSameType<T1, T2>::value;
int main()
{
cout << IsSame_v<int, int> << endl;
cout << IsSame_v<int, double><< endl;
cout << IsSame_v<int, const int><< endl;
system("pause");
return 0;
}
result :
边栏推荐
猜你喜欢

Props and context in setup

【MySQL从入门到精通】【高级篇】(七)设计一个索引&InnoDB中的索引方案

判断两个类型是否相同

软件测试面试思路技巧和方法分享,学到就是赚到

一文带你了解如何用SQL处理周报数据

Repeat: the difference between Pearson Pearson correlation coefficient and Spearman Spearman correlation coefficient
![[simple bug handling]](/img/25/3428978cabb79cdae5df6f98af6562.png)
[simple bug handling]

【无标题】

How to learn MySQL efficiently and systematically?

IBM:到2030年实现容错量子优势
随机推荐
从零开始的C
Summary of some open source libraries that drive MCU hardware debugger (including stlink debugger)
网站建设开始前要考虑的7个问题
Const char* in vs2022 cannot assign char*
transformer汇总
事件侦听和删除事件——event对象——默认事件——取消冒泡事件——事件委托——默认触发
不同类型的字段、集合list/set/map、对象如何判空null
C语言实战之猜数游戏
opensmile简介和安装过程中遇到的问题记录
券商真的有保本型理财产品吗?
【面试:并发篇21:多线程:活跃性】死锁、活锁、饥饿
Is it safe to buy shares and open an account? Will you lose money?
Repeat: the difference between Pearson Pearson correlation coefficient and Spearman Spearman correlation coefficient
作物叶片病害识别系统
我是新手,听说开户有保本的理财产品,是什么?
LeetCode 练习——关于二叉树的最近公共祖先两道题
wallys/WiFi6 MiniPCIe Module 2T2R2×2.4GHz 2x5GHz MT7915 MT7975
使用HiFlow场景连接器查看每天处于地区的疫情
Wallys/DR4019S/IPQ4019/11ABGN/802.11AC/high power
使用递归字符串反转和全排列