用多态函数覆盖模板函数 [英] Overriding a templated function with a polymorphic one
问题描述
如果我有
template<class T>
TalkyBuffer& operator<<(T const &object) { // Template
...
}
TalkyBuffer& operator<<(TalkySerialisable const &object); // Override
和一个班级
class A : public TalkySerialisable {
...}
然后我执行
TalkyBuffer b;
A test;
b << test;
然后,gcc会调用Template函数而不是Override函数
Then gcc is calling the Template function rather than the Override function
但是,如果我专门定义一个替代
However if I specifically define an override
TalkyBuffer& operator<<(A const &object); // Override without polymorphism
然后,gcc选择了那个. 有没有一种实用的方法可以用抽象类覆盖模板化函数?
Then gcc picks that one. Is there a practical way to override a templated function with an abstract class?
我读了这篇文章,但并没有阐明当您将多态性放入混合中时会发生什么: http://www.gotw.ca/publications/mill17.htm 另外,我在这里找不到解决方案,但也许我使用了错误的术语.
I read this but it doesn't shed light onto what happens when you throw polymorphism into the mix: http://www.gotw.ca/publications/mill17.htm Also I couldn't find a solution here but perhaps I'm using the wrong terms.
推荐答案
我认为可以使用基于function
的简单解决方案,重用函数重载进行推导.
I think it's possible to use a simple function
based solution, reusing function overload for derivation.
struct specialized {};
struct generic {};
template <class T>
TalkyBuffer& serialize(TalkyBuffer& buffer, T const& object, generic) {
...
}
generic dispatch(...) {} // always picked up last in overload resolution
template <class T>
TalkyBuffer& TalkyBuffer::operator<<(T const& object) { // Template
return serialize(*this, object, dispatch(object));
}
现在,让我们实现您的自定义类:
Now, let's implement your custom class:
TalkyBuffer& serialize(TalkyBuffer& buffer,
TalkySerialisable const& object,
specialized);
specialized dispatch(TalkySerialisable const&) {}
并创建一个派生的:
class A: public TalkySerialisable {};
那怎么办?
-
TalkyBuffer::operator<<(T const&)
将被接起 - 当尝试解决
serialize
的重载时,它将首先计算dispatch
的结果 - 解析
dispatch
的结果时,dispatch(TalkySerializable const&)
比dispath(...)
更好,因此返回类型为specialized
- 无法使用通用
serialize
(没有从specialized
到generic
的转换),因此继承就开始了
TalkyBuffer::operator<<(T const&)
will be picked up- when trying to resolve the overload for
serialize
, it will first compute the result ofdispatch
- when resolving the result of
dispatch
,dispatch(TalkySerializable const&)
is a better match thandispath(...)
, thus the return type isspecialized
- the generic
serialize
cannot be used (there is no conversion fromspecialized
togeneric
), so inheritance kicks in
这篇关于用多态函数覆盖模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!