部分模板专业化 - 成员专业化
假设我有这个模板类:
template<typename T> class MyClass{
public:
MyClass(const T& t):_t(t){}
~MyClass(){}
void print(){ cout << _t << endl; }
private:
T _t;
};
我想专门化它,所以类似地我定义:
template<> class MyClass<double>{
public:
MyClass(const double& t):_t(t){}
~MyClass(){}
void print(){ cout << _t << endl; }
private:
double _t;
};
现在,只要我们谈论小类,就可以了。如果我的课程很长,那么单独专门化 print()
会更明智。我知道如何使用非成员函数来做到这一点。有没有办法用成员函数来做到这一点?
Say I have this template class:
template<typename T> class MyClass{
public:
MyClass(const T& t):_t(t){}
~MyClass(){}
void print(){ cout << _t << endl; }
private:
T _t;
};
And I want to specialize it, so similarly I define:
template<> class MyClass<double>{
public:
MyClass(const double& t):_t(t){}
~MyClass(){}
void print(){ cout << _t << endl; }
private:
double _t;
};
Now, this is ok as long as we're talking about small classes. If I have a very long class, it would be a lot smarter to specialize print()
alone. I know how to do it with non-member function. Is there any way to do it with member functions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在您的示例中,您正在使用完全专业化。在这种情况下,您可以这样做:
但它不适用于部分专业化。
In your example, you are using full specialization. In that case, you can do it like this:
but it doesn't work for partial specialization.
化这个类模板(毕竟,它将是一个小类):
然后从中派生:
一个简单的解决方案是,定义包含您想要专门化的内容的基类模板,然后专门 不再需要专门化这个类模板;让它像你想要的那样大(并且合理)。
另一种选择是基于策略的设计,其中您将策略类作为模板传递类模板的参数(称为主机类)。
例如,
测试代码:
输出:
在线演示:http://ideone.com/r4Zk4
One straightforward solution is, define base class template containing things which you want to specialize, and then specialize this class template instead (it would be a small class, after all):
And then derived from it:
You don't need to specialize this class template anymore; make it as huge as you want (and reasonable).
Another alternative is policy-based design in which you pass policy-class(es) as template argument(s) to your class template (called host class).
For example,
Test code:
Output:
Online demo : http://ideone.com/r4Zk4
您可以专门为双精度打印成员函数:
<代码>
You can specialize your print member function specially for double:
在class.h中
在class.inl中
在class.cpp中
in class.h
in class.inl
in class.cpp