"无法从'A'转换为'B&'

"Cannot convert from 'A' to 'B&'

本文关键字:转换      更新时间:2023-10-16

我正在使用模板元编程构建一个实体组件系统。我不断收到Cannot convert from [base type] to [type user requested]&Cannot convert NullComponent to [type user requested]&错误:

class Entity {
public:
    Entity() = default;
    ~Entity() = default;
    template<typename C, typename... Args>
    void AddComponent(Args&&... args);
    template<typename C>
    C& GetComponent();
protected:
private:
    //...add/get helper methods here...
    unsigned int _id;
    std::vector<std::unique_ptr<IComponent>> _components;
};
template<typename C>
C& Entity::GetComponent() {
    for(auto c : _components) {
        if(std::is_base_of<a2de::IComponent&, C&>().value && std::is_same<decltype(c), C&>().value) {
            return *c; //<-- error here
        }
    }
    return NullComponent(); //<-- and here
}

编辑

这些选项现在似乎有效。

template<typename C>
const C& Entity::GetComponent() const {
    for(auto& uc : _components) {
        auto* c = dynamic_cast<C*>(uc.get());
        if(c && std::is_base_of<a2de::IComponent&, C&>().value && std::is_same<decltype(c), C&>().value) {
            return *c;
        }
    }
    throw std::runtime_error(std::string("Component not available."));
}

class Entity {
public:
    //same as before...
protected:
private:
    //same as before...
    a2de::NullComponent _null_component;
};
template<typename C>
const C& Entity::GetComponent() const {
    for(auto& uc : _components) {
        auto* c = dynamic_cast<C*>(uc.get());
        if(c && std::is_base_of<a2de::IComponent&, C&>().value && std::is_same<decltype(c), C&>().value) {
            return *c;
        }
    }
    return _null_component;
}

至少三件事:

  • GetComponent()中,您迭代unique_ptr元素,并将它们的类型(始终std::unique_ptr<IComponent>)与std::is_same中的其他内容进行比较。你可能不想这样。
  • 您似乎在最终返回中返回对临时的引用。
  • return *c需要dynamic_cast,除非 C == IComponent。

编辑

也:

  • std::is_base_of引用毫无意义。即使有class NullComponent : IComponent {};,你仍然会得到std::is_base_of<IComponent&, NullComponent&>::value == false
  • 并且您不检查空点

最后,在我看来,您应该将 for 循环替换为

for(auto& component : _components) {
  auto* c = dynamic_cast<C*>(component.get());
  if (c)
  {
    return *c;
  }
}

在高层次上,据我所知,返回类型不能用于定义模板类型。参数列表可用于定义模板类型。

所以,例如,这可能会起作用——

template<typename C>
void Entity::GetComponent(C *obj) {
    for(auto c : _components) {
        if(std::is_base_of<a2de::IComponent&, C&>().value && std::is_same<decltype(c), C&>().value) {
            obj = c; //<-- error here
            return;
        }
    }
    obj = NULL;
    return; //<-- and here
}

希望这有帮助。