https://godbolt.org/z/s5Yh8e6b8
I don't understand the reasoning behind this: why is explicit specialization with private type allowed for class templates but not for function templates?
Say we have a class:
class pepe
{
struct lolo
{
std::string name = "lolo";
};
public:
static lolo get()
{
return {};
}
};
- Class template can be explicitly specialized.
- And function templates have no problems upon implicit instantiation.
- Though you can't create
spec_class<pepe::lolo>{}
becausepepe::lolo
is inaccessable.
template <typename>
struct spec_class
{};
// this is ok
template <>
struct spec_class<pepe::lolo>
{};
// this will be ok also upon implicit instantiation
template <typename T>
void template_func(const T &t)
{
std::cout << "implicit: " << t.name << std::endl;
}
But:
// this is not ok!
// template <>
// void template_func(const pepe::lolo &p)
// {
// std::cout << "explicit: " << p.name << std::endl;
// }
// this is ok, but more or less understandable why
template <>
void template_func(const decltype(pepe::get()) &p)
{
std::cout << "explicit: " << p.name << std::endl;
}
// not ok, but expected
// void func(const pepe::lolo&)
// {}
So: Why is explicit specialization prohibited for a function template?
CodePudding user response:
From C 20, using private members in the parameter of a specialization of a function template is perfectly valid, due to PR0692. In particular, the following wording was added to temp.spec.general#6:
The usual access checking rules do not apply to names in a declaration of an explicit instantiation or explicit specialization, with the exception of names appearing in a function body, default argument, base-clause, member-specification, enumerator-list, or static data member or variable template initializer.
[ Note 1: In particular, the template arguments and names used in the function declarator (including parameter types, return types and exception specifications) can be private types or objects that would normally not be accessible. - end note]
(emphasis mine)
The code not compiling is due to a GCC bug 97942, and it compiles just fine in Clang. demo.