The template builder

Those worried about writing a lot of little classes are in luck. Most, if not all, of our builders will be the same except for the specific derived class they instantiate. That means we can use the power of C++ templates to create builders for us. Our templated builder will look like this:

//M5StageBuilder.h 
template <typename T>
class M5StageTBuilder : public M5StageBuilder
{
public:
virtual M5Stage* Build(void);
};

template <typename T>
M5Stage* M5StageTBuilder<T>::Build(void)
{
return new T();
}

This code works great for most of our stages. The only time it doesn't work is when we need to do something more specific, such as call a non-default constructor, or a function specific to the derived stage.

Notice that the implementation of the Build function is also included in the .h file. This is because template functions are not the same as regular functions. They work as recipes so the compiler knows how to generate the function for the specific type. Each time we need to use this function, the compiler will need to know about the recipe. This allows the compiler to instantiate the function as opposed to requiring the user to explicitly instantiate the Builder classes they need before using them. So when we want to use this class, it will look something like this:

//SomeFile.cpp 
#include "M5StageBuilder.h"
#include "MainMenuStage.h"

void SomeFunction(void)
{
//Creating the class needs the type
M5Builder* pBuilder = new M5StageTBuilder< SplashStage >();

//But using the Build function doesn't need the type
M5Stage* pStage = pBuilder->Build();
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.44.53