2

我的編譯器是gcc 4.9.0。以下代碼無法編譯:爲什麼gcc抱怨「錯誤:模板參數'0'的'intT'類型取決於模板參數」?

template<typename T, T i> 
struct value {}; 

template<typename T> 
struct value<T, 0> {}; 
// error: type 'T' of template argument '0' depends on a template parameter 

原因是什麼?以及如何解決這個問題?

+0

如何解決這個問題? - >請參閱以下問題的答案以獲得一些解決方法:[(部分)專門化依賴類型的非類型模板參數](http://stackoverflow.com/questions/22486386/partially-specializing-a-non-type - 依賴型模板參數/ 22486607#22486607)和[非依賴型非模板參數和可變模板](http://stackoverflow.com/questions/23228894/dependant-non-type-template-parameter-和可變參數模板?LQ = 1)。 – Constructor

回答

7

GCC是正確的,這是明確的C++ 11 [temp.class.spec]§8禁止:

8 Within the argument list of a class template partial specialization, the following restrictions apply:

  • A partially specialized non-type argument expression shall not involve a template parameter of the partial specialization except when the argument expression is a simple identifier. [ Example:

    template <int I, int J> struct A {}; 
    template <int I> struct A<I+5, I*2> {}; // error 
    template <int I, int J> struct B {}; 
    template <int I> struct B<I, I> {}; // OK 
    

    —end example ]

  • The type of a template parameter corresponding to a specialized non-type argument shall not be dependent on a parameter of the specialization. [ Example:

    template <class T, T t> struct C {}; 
    template <class T> struct C<T, 1>; // error 
    template< int X, int (*array_ptr)[X] > class A {}; 
    int array[5]; 
    template< int X > class A<X,&array> { }; // error 
    

    —end example ]

  • ...

我相信第2點是這裏最相關的一個。


關於「如何解決這個問題」的問題。在問題的立場上,恐怕沒有解決辦法。

至於原來vesion以使得整數序列,我相信你可以把它用uintmax_t的非類型模板參數的類型的工作,只有將其轉換爲intT在最後的定義。

+0

解決方案在哪裏? – xmllmx

+1

@Angew:天啊,我爲它而戰,它真的很固執......很高興你管理它! –

+0

@xmllmx你問爲什麼它不起作用,而不是如何使它工作。簡短的回答「這不行」。不過,最初的那個可能有不同的解決方案。但問題仍然是「爲什麼?」 – Angew