我使用模板元編程建立一個實體組分系統我不斷收到任何Cannot convert from [base type] to [type user requested]&
或Cannot convert NullComponent to [type user requested]&
錯誤:「無法從‘A’轉換爲‘B&’
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."));
}
OR
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;
}
分析循環,如果你發佈一個完整的樣本會更容易些,你想編譯(當前代碼丟失包括,IComponent和NullComponent)。 – Rumburak
你忘了在decltype中尊重'c'嗎? - >'std :: is_same()。value' - >'std :: is_same
在「似乎現在工作「解決方案,爲什麼你需要'std :: is_base_of'和'std :: is_same'? dynamic_cast不是照顧你需要的一切嗎?另外,我非常確定'is_base_of'中的引用停止了代碼的正常工作。 – Rumburak