2015-05-31 103 views
3

這在C法律++:專業模板類的功能

template <int N> class A { 
    void bar() {std::cout << N << '\n';} 
}; 

template<> 
void A<2>::bar() {std::cout << "Two\n";} // This is ok. 

現在考慮這個類:

template <int...> struct B; 

template <int First, int... Rest> 
struct B<First, Rest...> : B<Rest...> { 
    static void foo() { 
     std::cout << First << ' '; 
     B<Rest...>::foo(); 
    } 
    static void bar() {/*Bunch of code*/} 
    static void baz() {/*Bunch of code*/} 
}; 

template <> 
struct B<> { 
    static void foo() {} 
    static void bar() {} 
    static void baz() {} 
}; 

那爲什麼下面的非法(放在上面後):

template <int... Rest> 
void B<2, Rest...>::foo() { // Illegal. 
    std::cout << "Two "; 
    B<Rest...>::foo(); 
} 

我不明白爲什麼B<2, Rest...>是一個不完整的類型,如錯誤消息所述。顯然,實現我想要的唯一方法就是通過這個?

template <int... Rest> 
struct B<2, Rest...> : B<Rest...> { 
    static void foo() { 
     std::cout << "Two "; 
     B<Rest...>::foo(); 
    } 
    static void bar() {/*Same bunch of code as above*/} 
    static void baz() {/*Same bunch of code as above*/} 
}; 

因此重複bar()和baz()中的所有代碼?

+2

第一種是明確的特化(這是確定的);第二個是部分專業化(不是)。 –

回答

0

你試圖實現的是稱爲局部模板專門化,並且只允許用於類,而不是函數。例如參見Why function template cannot be partially specialized?

+0

我知道這個規則,但我認爲這裏的部分專業化更多的是與課堂相比,而不是功能。畢竟,錯誤信息指向'B <2, Rest...>'是一個不完整的類型。所以沒有令人滿意的解決方法,是嗎? – prestokeys

+1

該鏈接與此問題無關--OP並未嘗試部分專門化功能模板。 – Barry

+0

但是人們投票認爲我是。我還以爲我沒有試圖在發佈我的問題之前部分專門化功能模板。 – prestokeys