mercredi 25 mars 2015

Proper syntax to define simple object factory via operator new

Here is the basic outline of what I am trying to achieve



class Interface {
public:
virtual ~Base() {}
virtual void work() = 0;
static Interface *create();
static void setFactory(std::function<Interface *()>);
}


in Interface.cpp I have



static std::function<Interface *()> factory = nullptr;
Interface *Interface ::create() { return factory(); }
void Interface::setFactory(std::function<Interface *()> someFactory) {
factory = someFactory;
}


separately I have



class Implementation : public Interface {
...
}


And I made sure to call



Interface::setFactory([]() -> Interface * { return new Implementation(); });


prior to making any calls to Interface::create(). What I am seeing is that static factory variable is set (no longer a nullptr), so the call to setFactory did work. However resulting factory is empty and calls to Interface::create() would crash. I could probably find a workaround by making a structure with operator() but I wonder if there is an error in my lambda expression.


It is probably worth mentioning that I am using MSVC2013


Aucun commentaire:

Enregistrer un commentaire