我有一个使用未知T初始化的Child类型的对象。我需要创建一个与此对象具有相同类型T的新对象。我的Child类型的对象有一个未模板化的基类父类。我对类型为Child的对象的唯一访问是通过类型为Parent的指针。有没有可能将这个指向父对象的指针转换为指向正确模板化类型的子对象的指针?或者从指向父对象的指针中获取T?
我能找到的唯一例子在进行造型时已经知道T了。
struct Parent{
};
template <typename T>
struct Child{
typedef T ValueType;
};
template <typename T>
void foo(Parent*) { }
// implementation
Parent* object; // provided from somewhere else, points to Child<T> of unknown T
foo<T>(object); // PROBLEM because T depends on what T the Child in object was templated with发布于 2016-06-16 01:45:49
你的意思是像这样的东西(最小的例子)?
struct Parent {
virtual Parent * clone() = 0;
};
template<class T>
struct Child: Parent {
Child<T> * clone() override {
return new Child<T>;
}
};
int main() {
Child<int> *c = new Child<int>;
Child<int> *cclone = c->clone();
Parent *pclone = c->clone();
}编辑
考虑到OP通过编辑添加的代码片段,下面是一个稍微修改过的示例(基于相同的想法):
struct Parent;
template <typename T>
void foo(Parent*) { }
struct Parent{
virtual void invokeFoo() = 0;
};
template <typename T>
struct Child: Parent {
void invokeFoo() override {
foo<T>(this);
}
};
int main() {
Parent* object = new Child<int>;
object->invokeFoo();
}https://stackoverflow.com/questions/37841203
复制相似问题