Saturday, January 07, 2012

Singleton in a header only library

Static member variables are inevitable in singleton implementations. If we define the static member variable in the header file and include it in more than one source file, the linker would throw multiple definition errors when trying to link the translation units. So it is a little tricky to design the singleton in header only implementations. Nevertheless it is not difficult.

C++ allows static members variables of class templates to be defined in more than one translation unit. The linker would merge multiple definitions into one. This is found abundant in the Boost library.

If we don't want to use the templates, but stick with the definite class approach, then this is one way to achieve singleton in the header only library implementation.

Log.hpp - This provides a singleton logger instance.


main.cpp - A sample usage of the above library
Post a Comment