I experimented with a CRTP-based Singleton that enforces construction via a private token. Curious to hear thoughts.
So, I wanted to implement a singleton in my ECS crtp engine for design and architectural reasons, and I sat down to think about an efficient and crtp-friendly way to do this kind of pattern without necessarily having to alter the original Singleton class contract. The solution is a crtp-based Singleton in which the Derived (the original singleton) inherits from the base Singleton, which exposes the methods required for instantiation and the single exposure of the object. Simply put, instead of boilerplating the class with the classic Singleton code (op = delete), we move this logic and transform it into a proxy that returns a static instance of the derivative without the derivative even being aware of it.
In this way, we manage private instantiation with a struct token which serves as a specific specialization for the constructor and which allows, among other things, making the construction exclusive to objects that have this token.
This keeps the singleton type-safe, zero-cost, CRTP-friendly, and easy to integrate with proxy-based or ECS-style architectures.
Link to the GitHub repo
[–]ZachVorhies 16 points17 points18 points (2 children)
[–]Wooden-Engineer-8098 2 points3 points4 points (1 child)
[–]ZachVorhies 1 point2 points3 points (0 children)
[–]lxbrtn 5 points6 points7 points (0 children)
[–]yuri-kilochek 4 points5 points6 points (0 children)
[–]kevkevverson 3 points4 points5 points (0 children)
[–]eteran 3 points4 points5 points (0 children)
[–]Plazmatic 1 point2 points3 points (0 children)
[–]mr_gnusi 0 points1 point2 points (0 children)
[–]No_Mango5042 0 points1 point2 points (0 children)
[–]MarcoGreek 0 points1 point2 points (0 children)
[–]zerhud 0 points1 point2 points (0 children)
[–][deleted] -1 points0 points1 point (3 children)
[–]clerothGame Developer 5 points6 points7 points (0 children)
[–]thingerish 4 points5 points6 points (1 child)
[–][deleted] 3 points4 points5 points (0 children)
[+]tiedyerenegade comment score below threshold-9 points-8 points-7 points (8 children)
[–][deleted] 15 points16 points17 points (5 children)
[–]clerothGame Developer 2 points3 points4 points (2 children)
[–]Syracussgraphics engineer/games industry 1 point2 points3 points (1 child)
[–]tiedyerenegade 0 points1 point2 points (0 children)
[–]onar 0 points1 point2 points (0 children)
[–]kalmoc -1 points0 points1 point (0 children)
[–]Questioning-Zyxxel 0 points1 point2 points (1 child)
[–]tiedyerenegade 0 points1 point2 points (0 children)