October 22, 2024
Chicago 12, Melborne City, USA
templates

Friend declaration for template class in C++


#include <iostream>

class MyClass {
 public:
  template <typename U>
  friend class MyTemplateClass<U>;
};

int main() { return 0; }

The code provided above, tries to declare MyTemplateClass as a friend class to MyClass.

But, the issue arises when the compiler misinterprets it as specialization of template class MyTemplateClass which clearly, is not intended?

This works:

template <typename U>
friend class MyTemplateClass;

I do not understand why one would declare a type variable U, but would not use it in the friend declaration, If the purpose was to indicate that MyTemplateClass is a template class, then why can’t we directly use this?

template <>
friend class MyTemplateClass;



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video