2016-12-16 51 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

相关问题