Lean on the Compiler by Hiding (C++)

My Lean on the Java Compiler by Hiding post has proved quite popular so I've been thinking about if it could also work for C++... It can. I'll use Singleton as a example again. Suppose you have a C++ class like this:



class legacy
{
public:
    legacy();
    void eg1();
    void eg2();
    ...
};
#include "legacy.hpp"
#include "singleton.hpp"

void legacy::eg1()
{
    singleton::instance()->call();
}

void legacy::eg2()
{
    singleton::instance()->call();
}

Again, you want to create a seam for singleton access. The first step is to introduce the hiding identifier in the header file:

class legacy
{
public:
    legacy();
    void eg1();
    void eg2();
    ...
private:
    class singleton;  // <-----
};


Now Lean on the Compiler. All the calls to singleton::instance() no longer compile because the global singleton class is now hidden by the local singleton class just introduced. Next, in the source file add a global variable called instance of type singleton* and refactor all occurrences of singleton::instance() to instance.
#include "legacy.hpp"
#include "singleton.hpp"

singleton * instance;

void legacy::eg1()
{
    instance->call();
}

void legacy::eg2()
{
    instance->call();
}

Then Lean on the Compiler again to make sure there are no typos. Next remove the global variable called instance from the source file and refactor the header file to this:

class singleton; // <-----

class legacy
{
public:
    legacy();
    void eg1();
    void eg2();
    ...
private:
    singleton * instance; // <-----
};

Finally, initialize the instance member in the constructor definition.

legacy::legacy()
    : instance(singleton::instance())
{
}

I haven't tried this on real legacy code either. Caveat emptor!