2013-07-20 58 views
3

我有問題在類專業化中聲明一個不完整的結構體,然後再定義它。定義不完整的專業類結構

struct Foo { 
    template <bool Y, typename D> 
    struct Bar {}; 

    template <typename D> 
    struct Bar<true, D> { 
     struct Qux; 
    }; 

    template <typename D> 
    struct Bar<true, D>::Qux { int x; }; 
}; 

這個代碼在GCC,但在鐺3.3失敗:

r.cpp:42:26: error: non-friend class member 'Qux' cannot have a qualified name 
    struct Bar<true, D>::Qux { int x; }; 
      ~~~~~~~~~~~~~~^ 

如果代碼是寫在命名空間範圍(無struct Foo),它工作在鐺了。另一方面,如果struct Foo被轉換爲模板,如下所示,代碼在gcc-4.9(未發佈)中中斷,儘管它繼續在gcc-4.7中工作。

template <typename X> 
struct Foo { 
    template <bool Y, typename D> 
    struct Bar {}; 

    template <typename D> 
    struct Bar<true, D> { 
     struct Qux; 
    }; 

    template <typename D> 
    struct Bar<true, D>::Qux { int x; }; 
}; 

鏘失敗:

r.cpp:43:26: error: template specialization or definition requires a template parameter list corresponding to the nested type 'Bar<true, type-parameter-1-0>' 
    struct Bar<true, D>::Qux { int x; }; 
         ^
r.cpp:43:26: error: non-friend class member 'Qux' cannot have a qualified name 
    struct Bar<true, D>::Qux { int x; }; 
      ~~~~~~~~~~~~~~^ 
2 errors generated. 

GCC-4.9失敗,類似的錯誤:

r.cpp:43:26: error: too few template-parameter-lists 
    struct Bar<true, D>::Qux { int x; }; 
         ^

回答

2

貌似你沒有選擇,只能把那在命名空間範圍內定義(或在Bar內)。第9/1段(n3337)說你的代碼是非法的:

If a class-head-name contains a nested-name-specifier, the class-specifier shall refer to a class that was previously declared directly in the class or namespace to which the nested-name-specifier refers, or in an element of the inline namespace set (7.3.1) of that namespace (i.e., not merely inherited or introduced by a using-declaration), and the class-specifier shall appear in a namespace enclosing the previous declaration. In such cases, the nested-name-specifier of the class-head-name of the definition shall not begin with a decltype-specifier.

-3
struct Foo { 
    template <bool Y, typename D> 
    struct Bar {}; 
}; 

template <typename D> 
struct Foo::Bar<true, D> { 
    struct Qux; 
}; 

template <typename D> 
struct Foo::Bar<true, D>::Qux { 
    int x; 
}; 
+1

你能解釋爲什麼嗎? –

+0

-1只有代碼和沒有解釋的答案? – Manu343726