gpt4 book ai didi

c++ - 从 Parent* 转换为 Child* 且 T 未知,并得到 T

转载 作者:行者123 更新时间:2023-11-30 05:26:19 24 4
gpt4 key购买 nike

我有一个已用未知 T 初始化的 Child 类型的对象。我需要创建一个与此对象相同类型 T 的新对象。我的 Child 类型的对象有一个未模板化的基类 Parent。我对 Child 类型对象的唯一访问是通过 Parent 类型的指针。是否可以将指向 Parent 的指针转换为指向正确模板化类型的 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

最佳答案

你的意思是这样的(最小的例子)吗?

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();
}

关于c++ - 从 Parent* 转换为 Child<T>* 且 T 未知,并得到 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37841203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com