部分专业的模板朋友

时间:2013-08-13 14:49:20

标签: c++ templates friend

我有一个课程模板

template< typename G, int N > class Foo { /* ... */ };

我希望N=0的专业化成为另一个类的朋友,但我不知道它的语法(我自己也找不到它)。我试过了:

template< typename T >
class Bar {
  template< typename G > friend class Foo< G, 0 >;

  /* ... */
};

我希望任何类型G Foo< G, 0 >成为class Bar< T >的朋友。这个的正确语法是什么?

谢谢!

2 个答案:

答案 0 :(得分:2)

在C ++ 03中是不可能的; C ++标准14.5.3 / 9说明如下:

  

朋友声明不得声明部分专业化。

正如另一个答案中所述,此问题可能有一些变通方法,但您要求的特定功能在该标准中不可用。

幸运的是,C ++ 11现在得到了很好的支持,并且能够指定模板别名,我们可以实现这一目标:

template <typename, typename> struct X{};

template <typename T> 
struct Y
{
    template <typename U> using X_partial = X<T, U>;
    template <typename> friend class X_partial;
};

答案 1 :(得分:1)

没有C ++ 11我认为你能做的最好的是假类型别名,这可能需要一些代码(构造函数)重复(这可能无法解决你正在尝试的真正问题):

template< typename G, int N > class Foo { /* ... */ };

template<typename G> class FooAlias : public Foo<G, 0> { };

template< typename T >
class Bar {
  template< typename G > friend class FooAlias;

  /* ... */
};