Why does the Standard prohibit friend declarations

2020-06-08 07:39发布

问题:

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?

回答1:

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.



回答2:

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.