Base class with member parameterized on type of extending class

Jacob Carlborg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Oct 19 23:17:42 PDT 2014


On 2014-10-19 13:19, rcor wrote:
> I'm trying to make a game, and would like to set up the following
> hierarchy:
> At any time, the game is in one Scene. Each scene has a state machine
> that manages States of type T, where T is the type of the scene (e.g.
> Overworld, Menu).
>
> abstract class State!T {
>    void update(T scene, float time, InputManager input);
>    ...
> }
>
> class StateMachine!T { //manages states of type State!T }
>
> abstract class Scene {
>    alias T = // type of class extending Scene
>    // methods pushState, popState, currentState access _stateMachine
>    private StateMachine!T _stateMachine;
> }
>
> class MainMenu : Scene {
>     // I want _stateMachine of type StateMachine!MainMenu
> }
>
> class Overworld : Scene {
>    // I want _stateMachine of type StateMachine!Overworld
> }
>
> class MoveToLocation : State!Overworld {
>    override void update(Overworld world, float time, InputManager input) {
>      // access properties of Overworld here
>    }
> }
>
> Within the Scene class, I've tried alias T = typeof(this), but that
> appears to be resolved within Scene. This means that any Scene, such as
> Overworld, have a state machine of type StateMachine!Scene rather than
> StateMachine!Overworld. Since States are particular to a certain scene
> and are designed to manipulate properties specific to that type of
> scene, this would involve a lot of casting if States are not
> parameterized. It feels like I need something like a class version of
> the (this T) syntax used in templates.
>
> This all smells a bit off though, so I wouldn't be surprised if the
> answer is that I'm approaching this all wrong, but right now I'm not
> seeing it.

You can always make Scene a template class:

abstract class Scene (T)
{
     private StateMachine!T _stateMachine;
}

class MainMenu : Scene!(MainMenu) {}

But I'm guessing you like to avoid that if possible.

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list