Created
January 19, 2026 12:51
-
-
Save unrays/a04f929ef0ddd95d2e23ed6379a49c5a to your computer and use it in GitHub Desktop.
Modern C++ CRTP singleton implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Copyright (c) December 2025 Félix-Olivier Dumas. All rights reserved. | |
| // Licensed under the terms described in the LICENSE file | |
| template<typename Derived> | |
| struct Singleton { | |
| public: | |
| static Derived& instance() { | |
| static Derived instance(Token{}); | |
| return instance; | |
| } | |
| protected: | |
| struct Token {}; | |
| Singleton() = default; | |
| private: | |
| Singleton(const Singleton&) = delete; | |
| Singleton& operator=(const Singleton&) = delete; | |
| Singleton(Singleton&&) = delete; | |
| Singleton& operator=(Singleton&&) = delete; | |
| }; | |
| struct World final : Singleton<World> { | |
| friend Singleton<World>; | |
| void foo() const noexcept {} | |
| private: | |
| explicit World(Token) {} | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment