How would it be possible to solve a circular dependency caused by template functions?
For example, I have an Engine class defined that stores a list of Entities, and is responsible for creating entities and adding / removing components from them.
class Engine
{
public:
Entity CreateEntity();
template <typename T, typename... Args>
void AddComponentToEntity(Entity& entity, Args... args)
{
// Code to add component to entity
}
template <typename T>
void RemoveComponentFromEntity(Entity& entity)
{
// Code to remove component from entity
}
private:
std::vector<Entity> entities;
};
I have also then added functions within the entity class to "wrap" these functions, allowing a nice syntax for adding components to entities.
class Entity
{
public:
template <typename T, typename... Args>
void AddComponent(Args... args)
{
engine->AddComponentToEntity<T>(*this, args...);
}
template <typename T>
void RemoveComponent()
{
engine->RemoveComponentFromEntity<T>(*this);
}
private:
Engine* engine;
};
This allows me to write code like this
entity.AddComponent<PhysicsComponent>(Arguments..);
Instead of having to reference the engine object directly everywhere
engine->AddComponentToEntity(entity, Arguments..);
However, as the engine class contains entity instances, it has to include the Entity class. The Entity class then has to include the Engine class in order for the template functions to call the methods, which causes a circular dependency.
This could easily be solved if the functions were not templates, as the implementation could be put in Entity.cpp and then I could include the Engine class there. I am struggling to see how the same could be done with template functions.
You may do mostly as if the function were not template by splitting definition from declaration:
// Engine.h
// Engine.inl
And similarly for entity.h/entity.inl.