首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Parent*强制转换为带有未知T的Child<T>*,并获取T

从Parent*强制转换为带有未知T的Child<T>*,并获取T
EN

Stack Overflow用户
提问于 2016-06-16 00:42:56
回答 1查看 117关注 0票数 1

我有一个使用未知T初始化的Child类型的对象。我需要创建一个与此对象具有相同类型T的新对象。我的Child类型的对象有一个未模板化的基类父类。我对类型为Child的对象的唯一访问是通过类型为Parent的指针。有没有可能将这个指向父对象的指针转换为指向正确模板化类型的子对象的指针?或者从指向父对象的指针中获取T?

我能找到的唯一例子在进行造型时已经知道T了。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2016-06-16 01:45:49

你的意思是像这样的东西(最小的例子)?

代码语言:javascript
复制
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通过编辑添加的代码片段,下面是一个稍微修改过的示例(基于相同的想法):

代码语言:javascript
复制
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();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37841203

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档