为什么允许使用功能模板的私有类型的明确专业化?
https://godbolt.org/z/s5yh8e6b8
具有私有类型的明确专业允许类模板,但对于功能模板而言不允许使用?
假设我们有一个类:
class pepe
{
struct lolo
{
std::string name = "lolo";
};
public:
static lolo get()
{
return {};
}
};
- 可以明确专业化的类模板。
- 在隐式实例化时,功能模板没有问题。
- 尽管您无法创建
spec_class< pepe :: lolo> {}
,因为pepe :: lolo
是不可能的。
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;
}
但是:
// 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&)
// {}
所以: 为什么禁止对功能模板进行显式专业?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从C ++ 20中,在功能模板专业化的参数中使用私有成员是完全有效的,因为 pr0692 。特别是,以下措辞添加到 temp.spec.general#6 :
(强调矿山)
不编译的代码是由a GCC错误97942 ,它在clang中的编译很好。 demo 。
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:
(emphasis mine)
The code not compiling is due to a GCC bug 97942, and it compiles just fine in Clang. demo.