繁体   English   中英

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

[英]"Cannot convert from 'A' to 'B&'

我正在使用模板元编程来构建实体组件系统。 我不断收到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中的其他内容进行std::is_same 您可能不想要那样。
  • 看来,您要在最终申报表中返回对临时目录的引用。
  • 除非C == IComponent,否则return *c需要dynamic_cast。

编辑

也:

  • std::is_base_of对于引用没有意义。 即使使用class NullComponent : IComponent {}; ,您仍然会得到std::is_base_of<IComponent&, NullComponent&>::value == false
  • 而且您不检查nullptr

最后,在我看来,您应该将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
}

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM