Cant cast template argument
Im getting this error at the static cast line
Error C2440 'static_cast': cannot convert from 'ComponentType *' to 'ComponentStoreType *'
I get the exact same error from using dynamic_cast or reinterpret_cast, other than the cast name.
Any ideas?
template <typename ComponentType>
bool insertComponent(const Entity& entity, ComponentType& component) {
static_assert(std::is_base_of<ComponentStoreType, ComponentType>::value, "ComponentType must be derived from ComponentStoreType!");
if (storesComponentType<ComponentType>())
{
insertComponentVirtual(entity, static_cast<ComponentStoreType*>(&component));
return true;
}
else {
return false;
}
};
insertComponentVirtual is not templated and looks like
virtual void insertComponentVirtual(const Entity& entity, ComponentStoreType* component) = 0;
Edit: Solved by changing second parameter to be a const reference (To accept both lvalue and rvalue references). Also letting the call to insertComponentVirtual do an implicit conversion, and having insertComponentVirtual accept "pointer to const", instead of just a pointer as it were before.
template <typename ComponentType>
bool insertComponent(const Entity& entity, const ComponentType& component) {
static_assert(std::is_base_of<ComponentStoreType, ComponentType>::value, "ComponentType must be derived from ComponentStoreType!");
if (storesComponentType<ComponentType>())
{
insertComponentVirtual(entity, &component);
return true;
}
else {
return false;
}
};
virtual void insertComponentVirtual(const Entity& entity, ComponentStoreType const* component) = 0;
Posted Apr 19, 2019, 9:36 PM UTC · edited
19
Why do you need to cast? ComponentType is derived from ComponentStoreType. There should be an implicit conversion.
Thats what i did first, but i got this error
Edit: On the same line
You need to show more context. Try creating a standalone example that reproduces the error.
Alright, so i did this:
Error on manager->insertComponent line which is very similar to the one i was getting inside insertComponent:
But this type i also get the error:
If i change the main to:
i get no errors...
insertComponenttakes a lvalue reference, but you are passing it a temporaryDerived{ 5 }.You are trying to pass a temporary
Derived{5}by non-const reference. This is not allowed.