How to call a function on header inclusion?

I'm working on a simple framework for making 2D games. It uses components and systems, which will vary from game to game.

To make it easy for other parts of the engine to loop over all possible systems and / or components, I'd like them to let themselves be known the moment one of them is included (Each has their own header file), in a way creating a list of all possible component types and system types.

I've currently solved this by having a Register struct which is put at the bottom after a system or component definition, passing that component / system pointer as an argument to the constructer of the Register struct, i.e.:

std::vector<Component*> Components    
struct Register{
    Register(Component* newComponent){
        Components.push_back(newComponent);
    }
}

Which is then used at the bottom of each component's header:

 Register 2DPosReg(&2DPos);

Which makes sure that before we get to our main code all components are listed in Components. In the same fashion I also add the names of these components and some other details to some global vectors. However, it seems unnecesarily messy to create a temporary object that never gets used just to execute code in it's constructor.

Is there any other way where including the header will make itself 'known' to the rest of the code?

I'd like to avoid my previous solution where I had a long Register(&2DPos, &Vel, &Acc, ...etc) function that would register all options, as any changes to the used components would require re-editing this function.

(Also, first stackoverflow question, apologies if it's long / has beginners mistakes)

1 answer

  • answered 2018-11-08 08:44 StoryTeller

    However, it seems unnecesarily messy to create a temporary object that never gets used just to execute code in it's constructor.

    You are correct with your assessment of the solution's aesthetic qualities. Unfortunately C++ doesn't have a better mechanism to accomplish what you are after.

    After all, even the C++ standard library has to employ this technique when it wants to instrument code for execution after header inclusion.

    Though, since you did mark this C++17, and you intended to put the object declaration in a header, you need to make it an inline variable:

    inline Register whatevs(...);
    

    It should produce one object per-header file.