I was wondering if is it possible to create a class data member shared only by a group of objects of that same class.
I have a class called Scene, and another called GameObject, The Scene creates GameObjects, and each GameObject created must have a reference to the scene it creates it.
I could achieve this by just declaring:
class GameObject
{
public:
Scene* scene;
}
And put whenever a scene creates a gameobject.
void Scene::add_game_object(){
GameObject* gameobject = new GameObject();
gameobject->scene = this;
}
But, this would definitely take a lot of memory.
I was thinking about a solution, ( Currently not compiling but, may be we could shape something from that )
class GameObject
{
public:
template< Scene* S >
Scene* get_scene();
}
//
template< Scene* S >
Scene* GameObject::get_scene(){
static Scene* sc = nullptr;
if( sc == nullptr ){
sc = S;
}
return sc;
}
void Scene::add_game_object(){
GameObject* gameobject = new GameObject();
// link scene and gameobject.
gameobject->get_scene(this);
}
Using it :
gameobject->get_scene<nullptr>();
Thank you. Cordially.