为了这个问题,这被大大简化了。假设我有一个层次结构:
struct Base {
virtual int precision() const = 0;
};
template<int Precision>
struct Derived : public Base {
typedef Traits<Precision>::Type Type;
Derived(Type data) : value(data) {}
virtual int precision() const { return Precision; }
Type value;
};
我想要一个带有签名的非模板函数:
Base* function(const Base& a, const Base& b);
a
其中函数结果的具体类型与b
其中较大者的类型相同Precision
;类似于以下伪代码:
Base* function(const Base& a, const Base& b) {
if (a.precision() > b.precision())
return new A( ((A&)a).value + A(b.value).value );
else if (a.precision() < b.precision())
return new B( B(((A&)a).value).value + ((B&)b).value );
else
return new A( ((A&)a).value + ((A&)b).value );
}
其中A
和分别是和B
的具体类型。我想独立于有多少实例进行操作。我想避免使用大量的比较表,尽管 RTTI 的答案很好。有任何想法吗?a
b
function
Derived
typeid()