rkb
rkb

Reputation: 11231

how to declare a template class as a friend in c++

I wana know if we can make a partial specialized class as a friend class.

template< class A, class B >
class AB{};

class C;

template < class B >
class AB< C, B >{};

class D{
     template< class E > friend class AB< D, E >;
}

How to achieve the above.

Upvotes: 10

Views: 8778

Answers (2)

Luc Touraille
Luc Touraille

Reputation: 82071

This is not allowed by the C++ Standard (§14.5.3/9):

Friend declarations shall not declare partial specializations. [Example:

template<class T> class A { };
class X {
    template <class T> friend class A<T*>;   //error
};

--end example]

So basically, you can either make all instantiations of AB friend of D or only one particular instantiation. This IBM page describes the different relationships that can be achieved when it comes to friends and templates: "one-to-one", "one-to-many", "many-to-one" and "many-to-many" (but not "one-to-some" as you asked).

Upvotes: 8

Ofir
Ofir

Reputation: 2194

see the answer here, thanks to Drew Dormann

template <class T, class C>
class proxy {
   friend C;

It worked for me.

Upvotes: 1

Related Questions