0

In a class inheritance, base class's protected member is not available to outside but is available to derived class.

Like this, I wanted to make derived class's public member not available to outside but available to base class.

I got an idea that if derived class's member function has parameters which is base class's inner class, then it'll behave like reverse-protected member while it's still public.

I adjusted this idea writing singleton class with CRTP pattern.

template <typename T>
class Singleton
{
public:
    static auto& getinst()
    {
        static T inst = no_constructor_call{};
        return inst;
    }
    Singleton(const Singleton&) = delete;
    void operator=(const Singleton&) = delete;
 
protected:
    struct no_constructor_call {};
    Singleton() {}
};

I made a singleton backbuffer for draw image via double-buffering with winapi.

#define BackBuffer _BackBuffer::getinst()
class _BackBuffer : public Singleton<_BackBuffer>
{
public:
    void Draw(HDC h_dc)
    {
        buf_dc = CreateCompatibleDC(h_dc);
        HBITMAP bit_buf{ CreateCompatibleBitmap(h_dc, client.right, client.bottom) };
        SelectObject(buf_dc, bit_buf);
        BitBlt(h_dc, 0, 0, client.right, client.bottom, buf_dc, 0, 0, SRCCOPY);
        DeleteObject(bit_buf);
        DeleteDC(buf_dc);
    }
    operator HDC() { return buf_dc; }
 
    _BackBuffer(Singleton<_BackBuffer>::no_constructor_call) {}
 
private:
    HDC buf_dc;
};
  • _BackBuffer(Singleton<_BackBuffer>::no_constructor_call) {}
    

this line made class _BackBuffer's constructor is not available to outside code but available to the Singleton base.

So I could create the _BackBuffer object in Singleton class while preventing other code creating _BackBuffer objects.

If I made the constructor private, it couldn't have created in it's base class.

And If I made the constructor perfectly public, it could have created in other code so it's not guarantee as singleton.

Now I'm regarding it can expandable to when you are wanting some public member function to be not available except some regions.

Is there a design pattern like this already existing?

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
ArtLife
  • 36
  • 3
  • 1
    On a side note, why delete the copy constructor and copy assignment operator? Your `Singleton` class doesn't contain any non-static members or depend on its own address in any way. – alter_igel Aug 17 '21 at 15:42
  • Oh, force of habit. it was useless to delete copy constructor and copy assignment operator. – ArtLife Aug 17 '21 at 15:47
  • 1
    This comes up occasionally. I originally heard it called a lock and key pattern. Does this link help? https://stackoverflow.com/q/3220009/27678 – AndyG Aug 17 '21 at 15:49
  • Thanks! They helped me so much – ArtLife Aug 17 '21 at 15:52

0 Answers0