Skip to content

unrays/crtp-singleton

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 

Repository files navigation

A custom implementation of the Singleton design pattern, adapted to zero-cost CRTP architectures! I'm posting it here in case anyone finds the idea interesting :)

A small disclaimer: I'm just showing the work I'm proud of; I don't claim to have reinvented the Singleton because, let's face it, there's not really much to reinvent ;)

int main() {
    World::instance().foo(); //

    World instance; //
    World::foo() //
}
// 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) {}
};