如何使用模板模板参数专门化模板类的成员
我有一个带有 int 和模板模板参数的模板类。 现在我想专门化一个成员函数:
template <int I> class Default{};
template <int N = 0, template<int> class T = Default> struct Class
{
void member();
};
// member definition
template <int N, template<int> class T> inline void Class<N, T>::member() {}
// partial specialisation, yields compiler error
template <template<int> class T> inline void Class<1, T>::member() {}
谁能告诉我这是否可能以及我在最后一行做错了什么?
编辑:我要感谢大家的意见。由于我还需要对某些 T 进行专门化,因此我选择反对 Nawaz 建议的解决方法,并将整个类专门化,因为无论如何它只有一个成员函数和一个数据成员。
I have a template class with an int and a template template parameter.
Now I want to specialize a member function:
template <int I> class Default{};
template <int N = 0, template<int> class T = Default> struct Class
{
void member();
};
// member definition
template <int N, template<int> class T> inline void Class<N, T>::member() {}
// partial specialisation, yields compiler error
template <template<int> class T> inline void Class<1, T>::member() {}
Can anyone tell me if this is possible and what I am doing wrong on the last line?
EDIT: I'd like to thank everyone for their input. As I also need a specialization for some T, I opted against the workaround suggested by Nawaz and specialized the whole class, as it had only one member function and one data member anyway.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能部分特化单个成员函数,您必须为整个类执行此操作。
You can't partially specialize a single member function, you'll have to do it for the entire class.
由于这是不允许的,这里有一种解决方法:
想法是,当 N=1 时,函数调用
worker(int2type())
将解析为第二个函数(专业化),因为我们传递的是int2type<1>
类型的实例。否则,第一个(一般)功能将得到解决。As that is not allowed, here is one workaround:
The idea is, when N=1, the function call
worker(int2type<N>())
will resolve to the second function (the specialization), because we're passing an instance of the typeint2type<1>
. Otherwise, the first, the general, function will be resolved.在 C++ 中,不允许部分特化函数;您只能部分专门化类和结构。我相信这也适用于成员职能。
In C++ you are not allowed to partially specialize a function; you can only partially specialize classes and structures. I believe this applies to member functions as well.
查看这篇文章:http://www.gotw.ca/publications/mill17.htm
它非常小,并且有很好的代码示例。它将解释局部模板函数专门化的问题,并展示解决该问题的其他方法。
Check this article out: http://www.gotw.ca/publications/mill17.htm
It's pretty small, and has good code examples. It will explain the problem with patial template function specialization and show other ways around it.