C++ is_same


is_same

template< class T, class U >
struct is_same;

如果T與U具有同一const-volatile限定的相同類型,則is_same<T,U>::value為true,否則為false。

使用示例

#include<iostream>
#include<type_traits>
using namespace std;
int main()
{
    cout<<boolalpha;
    cout<<is_same<int,int>::value<<endl;
    cout<<is_same<int,double>::value<<endl;
}

輸出為

true
false

可能的實現

template<class T, class U> //0
struct is_same : std::false_type {};
 
template<class T> //1
struct is_same<T, T> : std::true_type {};

首先定義了一個類模板is_same,這個類模板有兩個模板參數T和U。接着針對這個類模板T和U類型相同的情況進行偏特化。所以,當T和U為同一種類型時,將匹配到1,不同則匹配到0。兩個版本唯一的不同是父類。

父類的定義:

using true_type=std::integral_constant<bool, true>
using false_type=std::integral_constant<bool, false>

可見true_typefalse_type是類模板std::integral_constant實例化的結果。

std::integral_constant可能的定義:

template<class T, T v>
struct integral_constant {
    static constexpr T value = v;
    typedef T value_type;
    typedef integral_constant type; // 使用注入的類名
    constexpr operator value_type() const noexcept { return value; }
    constexpr value_type operator()() const noexcept { return value; } // c++14 起
};

由代碼可見,std::integral_constant包裝了特定類型T的靜態常量,且值為v。

所以true_typefalse_type為包含一個靜態bool成員的類。值分別為true和false。

再以上面的代碼為例

當T,U都為int時,匹配到1,此時is_same類繼承了true_type,該類包含一個靜態bool對象value=true。
當T,U分別為int,double時,is_same類繼承了false_type,該類同true_type只不過value=false。

參考

http://zh.cppreference.com/w/cpp/types/is_same


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM