2017-02-23 88 views
0
template <int T> struct int2type{}; 

template<int I> 
void func(int2type<I>) 
{ 
    printf("int_val: %i\n", I); 
} 

int main(int argc, char *argv[]) 
{ 
    func(int2type<10>()); 
} 

當然它打印10無法理解C++模板11函數參數扣

我的模板和類型推導如何工作的一些基本的想法,但我無法理解這樣的代碼。 I背後的魔法是什麼?我們如何知道I from int2type實例傳遞給func

+3

我不明白這有什麼神奇的。編譯器希望某些'I'的參數爲'int2type '。你傳入一個類型爲'int2type <10>'的參數。編譯器對它們進行比較,並發現'I'必須是'10'才能使這兩種類型相同。 – Brian

+0

哦,是的!現在我看到它是如何工作的。謝謝! – sigmaN

回答

1

模板參數推導由C++ 14 Standard的section [temp.deduct.call]覆蓋。它完全不能完全重現,但要點是編譯器會將參數類型int2type<10>與參數類型int2type<I>進行比較,並嘗試找到I的值,這兩個值都相同。

在[temp.deduct.type]/9和它被指定/ 17,參數class-template-name<i>,其中i是非類型模板參數,由參數class-template-name<n>其中n是同一類型的參數相匹配。