具有多态性的模板专业化
我想通过使用指向其基本类型的指针来调用专门的模板函数。我不确定这是否可能,所以我愿意接受建议和/或替代方案。这是我的情况的一个例子:
class CBase {};
class CDerivedClass : public CBase {};
template<class T>
int func<T>(T &x) { ... };
template<>
int func<CDerivedClass>(CDerivedClass &x) { ... };
我有另一个函数来管理 CBase 指针列表,然后调用 func() 函数。
void doStuff()
{
CBase *foo[10] = { ...... };
for (int i = 0; i < 10; ++i)
func(*foo[i]);
}
有没有办法获取派生类型,以便调用 func(CDerivedClass &) ?
I'm wanting to invoke a specialized templated function by using a pointer to it's base type. I'm not sure if this possible so I'm open to suggestions and/or alternatives. Here is an example of my situation:
class CBase {};
class CDerivedClass : public CBase {};
template<class T>
int func<T>(T &x) { ... };
template<>
int func<CDerivedClass>(CDerivedClass &x) { ... };
I have another function that manages a list of CBase pointers and then calls the func() function.
void doStuff()
{
CBase *foo[10] = { ...... };
for (int i = 0; i < 10; ++i)
func(*foo[i]);
}
Is there a way to get the derived type, so that func(CDerivedClass &) is called?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
模板子类化怎么样?这个习惯用法允许您在 C++ 中使用编译时多态性。其代价是更加冗长(例如指定直到当前类的整个类层次结构)。在你的情况下:
What about Template Subclassing? This idiom allows you to use compile-time polymorphism in C++. The cost of it is higher verbosity (such as specifying the whole class hierarchy up to the current class). In your case:
在这种情况下,“访客”模式可以发挥作用。它允许在类外部实现的算法中实现多态行为。类内部需要一些支持代码,但以后可以添加新算法、修改现有算法等,而不会影响类。
The "Visitor" pattern comes to the rescue in this case. It enables polymorphic behavior in an algorithm implemented outside the class. Some support code is required inside the class, but new algorithms can later be added, existing algorithms modified, etc., without affecting the class.
替代解决方案:从您的示例中,很明显您应该在
CBase
中使用虚拟方法,因此您只需在CBase
中定义一个虚拟函数和一个重写函数在派生类中。Alternative solution : from your example, it's obvious that you just should to use a virtual method in
CBase
, so you just have to define a virtual function inCBase
and an overriding function in the derived class.