[C++-sig] C++ singleton

Wolfgang Langner wl at flexis.de
Mon Oct 24 12:50:30 CEST 2005


Hi,

> I am actually writing an interface to python for an existing C++ library 
> using Boost. This library has a C++ singleton class. This class has only one
> 
> constructor (with arguments) which is “protected” because it’s a singleton.
> 
> I am not able to build a Boost interface to this class because the 
> compiler complains that the constructor I have given to Boost
> 
> in the class_xxx constructor argument is not public (which is true) !

> Therefore, my question is simple : How is it possible to interface such 
> a class with only one constructor which is protected and a static method
> 
> to create/access the object ?

Don't export the constructor, use no_init.
Declare the static method which returns the only instance as staticmethod.

Example code, not tested:

class_<MySingleton, boost::noncopyable>("MySingleton", no_init)
       .def("get", &MySingleton::get, return_internal_reference<>())
       .staticmethod("get")
       ;

For more information see tutorial an reference:

http://www.boost.org/libs/python/doc/index.html

For code examples look at the unit tests or other projects using boost:python.


bye by Wolfgang



More information about the Cplusplus-sig mailing list