Base class with member parameterized on type of extending class
rcor via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Oct 20 04:54:06 PDT 2014
> If the state machine doesn't need to be exposed you can create
> base class for Scene which is not templated:
>
> abstract class Scene {} // As it is now minus the state machine
>
> abstract class ConcreteScene (T) : Scene
> {
> private StateMachine!T _stateMachine;
>
> // other code that need access to _stateMachine
> }
>
> class MainMenu : ConcreteScene!(MainMenu) {}
>
> Scene _currentScene = new MainMenu;
>
> "ConcreteScene" might not be the best name of an abstract class.
>
Just came up with something similar before I saw this post:
interface IScene { // enter, exit, update, draw }
class Scene!T : IScene {
private StateMachine!T _stateMachine;
void update(float time) {
_stateMachine.update(cast(T) this, time);
}
}
The cast is unfortunate but since it only happens once per update
cycle I'm not that worried about it.
>> I could just declare the StateMachine separately in every
>> Scene, but
>> that seems like a lot of duplicate code (I then repeat the
>> same code for
>> updating the state machine, ect.)
>
> Or you could use a template mixin:
>
> template StateMachineMixin (T)
> {
> private StateMachine!T _stateMachine;
>
> // other code that need access to _stateMachine
> }
>
> class MainMenu : Scene
> {
> mixin StateMachineMixin!(typeof(this));
> }
Interesting idea, I might give this a try but the first
suggestion seems fine for now. Thanks!
More information about the Digitalmars-d-learn
mailing list