17

The C++ standard prohibits friend declarations of partial specializations. (§14.5.3/8):

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]

Other questions, e.g. this one, have received answers that invoke this prohibition, but I would like to know the rationale. I don't see it and can't find it with my favourite search engine. I can find however that it goes right back to the C++98 standard, so presumably the rationale is quite basic and clear. Can someone explain it to me?

Community
  • 1
  • 1
Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182

2 Answers2

2

I don't have a reference but I suspect that this is because it would result in the partial specialization being declared in the scope of the friend-declaring class rather than the scope of the template in question, and rather than creating a bunch of rules to force the friend declaration to result in the specialization being in the correct scope, they simply prohibit it.

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • Thanks for your answer, but it is speculative. There must be a definitive answer and people who know it, so I'll hold out. – Mike Kinghan May 16 '13 at 13:32
0

Here is some undirect explanation: http://www.cprogramming.com/tutorial/template_specialization.html

A final implementation detail comes up with partial specializations: how does the compiler pick which specialization to use if there are a combination of completely generic types, some partial specializations, and maybe even some full specializations? The general rule of thumb is that the compiler will pick the most specific template specialization--the most specific template specialization is the one whose template arguments would be accepted by the other template declarations, but which would not accept all possible arguments that other templates with the same name would accept.

I infer that maybe it is not permitted to prevent any ambiguity in the determination of specialization type.

fatihk
  • 7,789
  • 1
  • 26
  • 48
  • Can you give an example where it would (if allowed) cause the picking of a specialization to be ambiguous? – David May 15 '13 at 14:21
  • @faith_k, Thanks for your answer, but it is speculative. There must be a definitive answer and people who know it, so I'll hold out. – Mike Kinghan May 16 '13 at 13:33
  • I don't buy this at all. Although the resolution rules may be complex, they still decide on a particular case. And the general "friend template" specifier actually makes all specializations friends as well. Why couldn't the partial-specialization friend specifier simply apply to all specializations (including instantiations) which matched the specified pattern? – davmac Jun 03 '16 at 10:53