這是一段代碼
// check if type of static array
template <class T>
struct ABIStaticArray : std::false_type //#1
{
};
// stringN type => bytesN
template <std::size_t N>
struct ABIStaticArray<std::array<char, N>> : std::false_type //#2
{
};
// a fixed-length array of N elements of type T.
template <class T, std::size_t N>
struct ABIStaticArray<std::array<T, N>> : std::true_type //#3
{
};
// fixed length of type, default 1 except static array type
template <class T, class Enable = void>
struct Length //#4
{
enum
{
value = 1
};
};
// length of static array type
template <class T>
struct Length<T, typename std::enable_if<ABIStaticArray<T>::value>::type> //#5
{
enum
{
value = std::tuple_size<T>::value * Length<typename std::tuple_element<0, T>::type>::value
};
};
- 為什么 Length 的專用模板中的 std::enable_if 只有第一個引數?
- 如果我傳入一個StaticArray,它如何匹配Length的專用模板,如果Length的專用模板中std::enable_if的第一個引數的值為true,則專用模板將變為:
template <class T>
struct Length<T, void>
{
enum
{
value = std::tuple_size<T>::value * Length<typename std::tuple_element<0, T>::type>::value
};
};
為什么需要這個專門的模板,和Length的基本模板有什么區別?長度的呼叫喜歡:
Length<std::array<int, 5>>::value
結果是 5
請幫忙,非常感謝!
uj5u.com熱心網友回復:
讓我們一步一步來看看發生了什么。當你寫道:
Length<std::array<int, 5>>::value
步驟 1)的模板引數T為Lengthstd::array<int, 5>
步驟 2)現在有兩個選項可以使用。template <class T, class Enable = void>標記為的主模板#4或靜態陣列的特化#5。我們想找出應該使用哪一個。為此,條件typename std::enable_if<ABIStaticArray<std::array<int, 5>>::value>::type被測驗。
步驟 3)現在,ABIStaticArray<std::array<int, 5>>使用標記為 的第二個專業化,#3因為它比第一個專業化更專業化,#2并且來自主模板#1。
步驟 4)由于使用了第二個特化,因此std::enable_if<ABIStaticArray<std::array<int, 5>>::value計算結果為。基本上,專業化的優先于主要模板。truetypename std::enable_if<ABIStaticArray<std::array<int, 5>>::value>::typevoidLength
步驟 5)由于Length選擇了 的專業化,因此value使用計算得出value = std::tuple_size<std::array<int, 5>>::value * Length<typename std::tuple_element<0, std::array<int, 5>>::type>::value的結果是5。
為了確認這一點,我稍微修改了您的程式:
// length of static array type
template <class T>
struct Length<T, typename std::enable_if<ABIStaticArray<T>::value>::type> //#5
{
enum
{
value = std::tuple_size<T>::value * Length<typename std::tuple_element<0, T>::type>::value
};
Length()
{
std::cout <<"specialization #5"<<std::endl;
}
};
int main()
{
Length<std::array<int, 5>> v; //will use the specialization of Length
}
作業演示。
程式的輸出是:
specialization #5
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/519910.html
標籤:C 模板
上一篇:模板扣除依賴于另一個模板扣除
