So reading through the SFML book, I came across some code regarding the Finite State Machine that I do not comprehend. I understand that what I am about to ask may be a C++ question and not necessarily an SFML question but I couldn't find any helpful resources online anywhere that would better my understanding.
My question is in regards to these bits of code:
// StateStack.hpp
typedef std::unique_ptr< State > StatePtr;
class StateStack
{
//.....
std::map< States::ID, std::function< State::StatePtr() > > m_factories;
};
template< typename T >
void StateStack::registerState( States::ID )
{
m_factories[ id ] = [ this ] () { return State::StatePtr( new T(*this, m_context ) ); };
}
//StateStack.cpp
State::StatePtr StateStack::createState( States::ID id )
{
auto found = m_factories.find( id );
assert( found != m_factories.end() );
return found -> second();
}
I guess you could say I'm wondering why std::function is used inside of the m_factories map instead of just say, an std::unique_ptr< State > ? Would it not be possible to use that method and store a new smart pointer in the registerState() method, then just return the smart pointer stored in there by reference in the createState() method? Or is there a specific reason as to why using std::function is more effective? Also I thought that std::function was to be used with functors or functions? Does this mean that a unique_ptr can be used as one of those?
Again sorry if this is more of a C++ question but seeing as it's part of an SFML project I thought I could get some help here. Thanks