有以下简化数据结构:
Object1.h
template <class T> class Object1 { private: T a1; T a2; public: T getA1() {return a1;} };
Object2.h
template <class T> class Object2: public Object1 <T> { private: T b1; T b2; public: T getB1() {return b1;} }
Functions.h
template <class Object> void (Object *o1,Object *o2) { T = o1.getA1(); //Is it possible to get T from object o1? ... }
或者我们必须提供有关两个对象的数据类型的其他信息:
template <class T,class Object> void (Object *o1,Object *o2) { T = o1.getA1(); ... }
解决方法
添加一个typedef:
template <class T> class Object1 { private: T a1; T a2; public: T getA1() {return a1;} typedef T type; }; template <class Object> void foo(Object *o1,Object *o2) { typename Object::type x = o1.getA1(); ... }