gpt4 book ai didi

c++ - 这样的垂头丧气安全吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:29:43 24 4
gpt4 key购买 nike

假设我们有以下代码:

#include <memory>
#include <vector>

struct BaseComponent
{
template <typename T>
T * as()
{
return static_cast<T*>(this);
}

virtual ~BaseComponent() {}
};

template <typename T>
struct Component : public BaseComponent
{
virtual ~Component() {}
};

struct PositionComponent : public Component<PositionComponent>
{
float x, y, z;

virtual ~PositionComponent() {}
};

int main()
{
std::vector<std::unique_ptr<BaseComponent>> mComponents;
mComponents.emplace_back(new PositionComponent);

auto *pos = mComponents[0]->as<PositionComponent>();
pos->x = 1337;

return 0;
}

在 T * as() 方法中,我应该使用 static_cast 还是 dynamic_cast?有时转换会失败吗?我需要像这样 dynamic_cast 吗?

    auto *ptr = dynamic_cast<T*>(this);

if(ptr == nullptr)
throw std::runtime_error("D'oh!");

return ptr;

最佳答案

在你的情况下,没有办法静态地判断 this 是否是正确的类型。您可能想要的是 CRTP(奇怪的重复模板模式):

template <class T>
struct BaseComponent
{
T* as()
{
return static_cast<T*>(this);
}

virtual ~BaseComponent() {}
};

template <typename T>
struct Component : public BaseComponent<T>
{
virtual ~Component() {}
};

struct PositionComponent : public Component<PositionComponent>
{
float x, y, z;

virtual ~PositionComponent() {}
};

这样你就可以做到:

auto x = yourBaseComponent.as();

并让正确的 child 静态输入。

关于c++ - 这样的垂头丧气安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18195812/

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