为了解决这个问题,这非常简化。说我有一个层次:基于模板参数在C++中模拟动态调度
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
是特定类型的分别a
和b
。我想要function
独立于有多少个实例Derived
进行操作。我想避免比较大规模的typeid()
表,虽然RTTI很好的答案。有任何想法吗?
我想你应该提到你不知道完整的类的类型。你只知道'Base&'。包括我自己在内的几个答案确实假设你知道确切类型'Derived '。 – 2010-03-12 22:15:11
注意对一个答案的评论:另一个要求是该函数不能是一个模板;它必须具有给定的Base *(Base&Base)签名。 – 2010-03-12 22:20:12
将限制更清楚地纳入问题中。 – 2010-03-12 22:23:26