0

Is it possible to make the friend class a template, such as :

template <class T>
class MyClass {
public:
    friend class T;
};

The reason why I'm striving to get this is that I'm using policy-based design and I want my policy classes to access the host members. (...now I begin to think that this might mean my design is simply bad... )

Thanks in advance guys!

Shnippoo
  • 193
  • 2
  • 10

1 Answers1

4

In C++03 you are not allowed to declare friendship to an argument of the template.

§7.1.5.3/2

[...] If the identifier resolves to a typedef- name or a template type-parameter, the elaborated-type-specifier is ill-formed. [Note: this implies that, within a class template with a template type-parameter T, the declaration

       friend class T;

is ill-formed. ]

In C++11 there has been some changes to this respect, but it is a bit weird. friend class T; is still illformed, but friend T is allowed. A quote can be found in the same paragraph:

§7.1.5.3/2

[...] [ Note: This implies that, within a class template with a template type-parameter T, the declaration

 friend class T;

is ill-formed. However, the similar declaration friend T; is allowed (11.3). — end note ]

Notes are not normative, but they indicate the intent of the norms around it. I have not been able to find the specific sentence that makes the note correct, but I assume that at least the intention is that this should be allowed.

Community
  • 1
  • 1
David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489