简体   繁体   English

部分专业的模板朋友

[英]Partially specialized template friends

I have a class template 我有一个课程模板

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

I want the specialization for N=0 to be a friend of another class, but I don't know the syntax for it (and I could not find it out myself). 我希望N=0的特化是另一个类的朋友,但我不知道它的语法(我自己也找不到它)。 I tried: 我试过了:

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

  /* ... */
};

I want for any type G Foo< G, 0 > to be a friend of class Bar< T > . 我希望任何类型G Foo< G, 0 >成为class Bar< T >的朋友。 What is the correct syntax for this? 这个的正确语法是什么?

Thank you! 谢谢!

In C++03 that is not possible; 在C ++ 03中是不可能的; the C++ standard 14.5.3/9 says the following: C ++标准14.5.3 / 9说明如下:

Friend declarations shall not declare partial specializations. 朋友声明不得声明部分专业化。

As noted in another answer, there may be some workarounds for this issue, but the specific functionality you are asking for is not available in that standard. 如另一个答案所述,此问题可能有一些解决方法,但您要求的特定功能在该标准中不可用。

Luckily, C++11 is quite well supported nowadays, and with the ability to specify template aliases, we can achieve just this: 幸运的是,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;
};

Without C++11 I think the best you can do is a fake type alias, that may require some code (constructor) duplicatation (which may not solve the real problem you're attempting): 没有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;

  /* ... */
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM