2016-12-16 32 views
4

說我有一個模板(助手)類,並且我想讓模板的所有實例化類成爲朋友(所以我可以隱藏一些靜態成員函數爲私有,即使它們偶爾會在內部切換模板參數)。是否可以將模板的所有實例化類聲明爲相互爲朋友?

像這樣:

template </* some types */> 
class Foo { 
    template </* same as above types */> 
    friend class Foo</* template arguments */>; 
    // ... 
}; 

但是,這不會編譯因爲GCC警告我說,我是專業一些模板這是不允許的(必須出現在命名空間內)。我並不想專門做任何事情......

有沒有辦法做到這一點?


本來,因爲有很多很多爭論,我試圖用可變參數模板來節省一些打字,但是這被認爲由編譯器的專業化。雖然後來我切換回輸入所有參數,但調用顯式特化(保留<>)。

非常原始代碼:

template <class... Ts> 
friend class Foo<Ts...>; 
+0

@RyanHaining,其實很相似,謝謝 – YiFei

回答

9

是的,你可以,只要使用正確的語法template friends declaration。例如(解說寫在評論中)

template <T> 
class Foo { 
    // declare other instantiations of Foo to be friend 
    // note the name of the template parameter should be different with the one of the class template 
    template <typename X> 
    friend class Foo; // no </* template arguments */> here, otherwise it would be regarded as template specialization 
}; 
+0

啊哈!太棒了,所以我的原始代碼使用專業化語法...非常感謝。 – YiFei

相關問題