简体   繁体   中英

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). 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 > . What is the correct syntax for this?

Thank you!

In C++03 that is not possible; the C++ standard 14.5.3/9 says the following:

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:

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):

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;

  /* ... */
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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