C ++ template method for creating objects

I use Luabind to expose my Lua game engine. I recently encountered difficulties when I found out that I was not able to create a “new” one, for example. GUIObject * obj = new GUIObject () in Lua, and everything created in Lua belongs to Lua.

Well, that wasn't a huge problem, I decided to just create some kind of Factory template for objects, for example. my GUIManager has

class GUIManager {
template <class T> T * CreateObject( T classType )
{
    return new T();
}
}

My Luabind bindings are as follows:

class_<GUIManager>("GUIManager")
         .def("CreateObject", (GUILabel*(GUIManager::*)(GUILabel classType))&GUIManager::CreateObject<GUILabel>)
         .def("CreateObject", (GUIImage*(GUIManager::*)(GUIImage classType))&GUIManager::CreateObject<GUIImage>)

Everything works in Lua, calling:

testLabel = theGUI:CreateObject(GUILabel())

However, I feel that this is not “correct”, since I essentially create an object for transfer, I am sure that there is an easier way, but all other methods that I have tried so far are not consistent with either the compiler or Luabind .

Feel free to request additional information if necessary.

thank

+5
1

Luabind CreateObject, :

class_<GUIManager>("GUIManager")
         .def("CreateLabel", /*...*/&GUIManager::CreateObject<GUILabel>)
         .def("CreateImage", /*...*/&GUIManager::CreateObject<GUIImage>)

Lua "":

testLabel = theGUI:CreateLabel()

factory.

class GUIManager {
    template <class T> T * CreateObject() { return new T(); }
};
+3

All Articles