2017-02-07 88 views
2

在下面的代碼中,當模板參數T的值爲B<m>時,我嘗試專門化基類A模板專業化的不正確實例化

#include <array> 
#include <iostream> 

template <std::size_t m> 
struct B 
{ 
    std::array<double,m> arr; 
}; 


template <std::size_t n, typename T> 
struct A 
{ 
    std::array<T,n> arr; 
    const static int inner_dim = T::inner_dim; 
}; 

template <std::size_t n > 
template <std::size_t m> 
struct A<n,B<m>> 
{ 
    std::array<B<m>,n> arr; 
    const static int inner_dim = m; 
}; 


int main(int argc, char *argv[]) 
{ 
    A<5,A<4,B<3>>> a; 
    std::cout << a.inner_dim << std::endl; 

    A<5,B<4>> b; 
    std::cout << b.inner_dim << std::endl; 

    return 0; 
} 

然而,在主要的實例,我收到以下錯誤,當我編譯使用g ++ 5.4:

$ g++ -Wall --std=c++11 specialization.cc 
specialization.cc: In instantiation of ‘const int A<4ul, B<3ul> >::inner_dim’: 
specialization.cc:15:20: required from ‘const int A<5ul, A<4ul, B<3ul> > >::inner_dim’ 
specialization.cc:30:18: required from here 
specialization.cc:15:20: error: ‘inner_dim’ is not a member of ‘B<3ul>’ 
    const static int inner_dim = T::inner_dim; 
        ^
specialization.cc: In instantiation of ‘const int A<5ul, B<4ul> >::inner_dim’: 
specialization.cc:33:18: required from here 
specialization.cc:15:20: error: ‘inner_dim’ is not a member of ‘B<4ul>’ 

看來只能用於一般的定義,從來沒有專業化。我如何確保實現正確的專業化?

+0

注:鐺拒絕嘗試專業化 –

回答

6

我的猜測是

template <std::size_t n > 
template <std::size_t m> 
struct A<n,B<m>> 

應該

template <std::size_t n, std::size_t m> 
struct A<n,B<m>> 
+0

是的,就是這樣。奇怪的。我確信我以前曾嘗試過。謝謝! – kalj