部分专业化成员函数实现
我目前正在重构一些代码,明确专门化具有两个模板参数的类模板的成员函数。
template <class S, class T>
class Foo
{
void bar();
};
template <class S, class T>
void Foo<S, T>::bar()
{ /* Generic stuff */ }
template <>
void Foo<SomeType, SomeType>::bar()
{ /* Some special function */ }
现在我添加了一些更多的模板参数,因此该类现在如下所示:
template <class S, class EXTRA0, class T, class EXTRA1>
class Foo
{
void bar();
};
这两个额外的参数只是将 typedef 添加到我的类中,因此运行时功能并没有真正改变。有什么方法可以保留 bar 的(现在部分)专门实现吗?我似乎无法弄清楚它的语法,而且我有预感这可能是不可能的。
编辑:我正在寻找类似的东西:
template <class EXTRA0, class EXTRA1>
void foo<SomeType, EXTRA0, Sometype, EXTRA1>::bar()
{
/* specialized implementation */
}
它似乎无法编译..
I'm currently refactoring some code the explicitly specializes a member function of a class template with two template parameters.
template <class S, class T>
class Foo
{
void bar();
};
template <class S, class T>
void Foo<S, T>::bar()
{ /* Generic stuff */ }
template <>
void Foo<SomeType, SomeType>::bar()
{ /* Some special function */ }
Now I added some more template parameters, so the class now looks like this:
template <class S, class EXTRA0, class T, class EXTRA1>
class Foo
{
void bar();
};
These two extra parameters just add typedefs to my class, so the run-time functionality doesn't really change. Is there any way I can keep the (now partially) specialized implementation of bar? I can't seem to figure out the syntax for that and I have a hunch that it might not be possible.
Edit: I'm looking for something like:
template <class EXTRA0, class EXTRA1>
void foo<SomeType, EXTRA0, Sometype, EXTRA1>::bar()
{
/* specialized implementation */
}
which does not seem to compile..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你是对的,这是不可能的。
您可以做的是在新的
Foo
中创建一个辅助成员类模板,并将专用函数作为非模板成员函数放置在其中。专门化辅助类而不是函数。另一种选择是将专业化转变为非模板重载。
You are correct, it is not possible.
What you can do is create a helper member class template inside the new
Foo
, and place the specialized function inside it as a non-template member function. Specialize the helper class instead of the function.Another alternative is to turn the specialization into a non-template overload.
我不认为你想要的事情那么容易实现。像这样的事情怎么样:
I do not think that what you want is that easily possible. What about something like this:
您可以通过使用专用函子而不是函数来实现这一点:
You can achieve that by using a specialize functor instead a function :
您可以创建 Base class ,您可以在其中定义除 bar() 之外的所有成员,然后创建派生类(一个用于通用目的,一个用于 SomeType):
You can make Base class , where you can define all your members except bar() and then create derivative classes(one for general purpose, one for SomeType):