Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 720
Sh4pe Avatar asked Oct 21 '22 03:10

Sh4pe


2 Answers

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;
};
like image 157
nijansen Avatar answered Oct 24 '22 04:10

nijansen


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;

  /* ... */
};
like image 23
Mark B Avatar answered Oct 24 '22 03:10

Mark B