0

I have a two template class, templateClass1 and templateClass2. I want to use private variables and methods of templateClass1 in templateClass2. Is it possible to do so by using friend keyword in c++ ?

Sumit

slonkar
  • 4,055
  • 8
  • 39
  • 63

2 Answers2

1

I know this post is probably dead, but for other people who stumble upon this...

templateClass1.h

template <class T> class templateClass2;    // forward declare

template <typename T>
class templateClass1 {
    friend templateClass2<T>;
};

templateClass2.h

template <class  T> class templateClass1;    // forward declare

template <typename T>
class templateClass2 {
    friend templateClass1;
}
-1

It is possible to have a friends of any type, but a template is not a type until its template arguments have been supplied. So in general you would have to have a specialization for each full type you wish to be friends with. This will push you toward attempting to pass the type to be friend as a template parameter, but you can not supply a template type that will be friended.

for ex. this is illegal

template <class T> 
class A
{
     friend class T;
};

with those stipulations it makes it very difficult to do anything meaning full with templates and friendedness.

rerun
  • 25,014
  • 6
  • 48
  • 78
  • The syntax is just `friend T;` since the compiler has already been told that `T` is a type. – Ben Voigt Mar 26 '12 at 00:54
  • You can friend a base class but you still then have to provided accessors because friendship can not be inherited. – rerun Mar 26 '12 at 00:55
  • In C++03 you had to say `friend class identity::type;` rather than `friend T;` – Ben Voigt Mar 26 '12 at 00:56
  • http://stackoverflow.com/questions/702650/making-a-template-parameter-a-friend From another SO question covering the topic – rerun Mar 26 '12 at 00:58
  • For every specialization of templateClass2 to be friend of templateClass2 or something else ? friend templateClass2 – milyaaf Mar 26 '12 at 11:03