作者mikukonn (mikukon)
看板C_and_CPP
标题[问题] C++ STL function common_type 实作行为
时间Sun Sep 16 22:05:48 2018
各位大大好,最近小弟在看 C++ 17 STL ,在这之中看到了 common_type 这个函数
此函数的用途为在两种型态中选出不会窄化(Narrowing)之形别
此函数的实做如下
template<class T1, class T2>
struct common_type {
using type = decltype(false ? declval<T1>() : declval<T2>());
}
小弟我不太懂此函数是如何做到筛选形别的
小弟的理解是在 ?: 运算子中将会先评估 declval<T2>() 从而得到型别 T2 (或其衍生物)
但是此函数每次都能得到应有的型别,例如
common_type<int, float> ::type; // float
common_type<int, long> ::type; // long
common_type<float, unsigned long>::type; // float
还请各位大大解惑
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 43.243.253.180
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1537106750.A.821.html
※ 编辑: mikukonn (43.243.253.180), 09/16/2018 22:06:46
※ 编辑: mikukonn (43.243.253.180), 09/16/2018 22:07:31
1F:→ mikukonn: 阿我看懂了,因为 ?: 运算子必须找出一个形别来回传 09/16 22:11
2F:推 Sirctal: 不错!!! 标题改一下已解决 09/17 21:11