Two small tools to make things more static

Hi all, there are 2 very small utilities I wrote a long time ago and that I use very often. I wonder if something like this has already been provided somewhere: The first is a small class template static_ which create a singleton of a class "from outside". It can be either instantiated: struct AnyClass { void f() {} }; static_<AnyClass> s; s->f(); ...or used completely statically: static_<AnyClass>::get()->f(); AnyClass must be default constructible; it's guaranteed that all static_<AnyClass> instances will only create one single instance of AnyClass. static_ has a second (defaulted) template parameter to specify an "owner" type. You can specify it if you want a single instance for exactly one owner type; (so, if A and B are classes, static_<AnyClass, A> and static_<AnyClass, B> would produce one static instance for A and one for B). The purpose of the second utility ("call") is to make a "static call" (=call once); it does nothing else then to call a functor in its constructor so that you can write static call c(functor); See attachements! Cheers, Stefan #ifndef STATIC_TOOLS_H_INCLUDED #define STATIC_TOOLS_H_INCLUDED /* Some ideas for static tools ... (c) Stefan Slapeta 2004 */ //////////////////////////////////////// // class template static_ //////////////////////////////////////// template <typename T, typename OwnerT = void> struct static_ { T* operator -> () const { return &member; } static T* get() { return &member; } private: static T member; }; template <typename T, typename OwnerT> T static_<T, OwnerT>::member; //////////////////////////////////////// // class call //////////////////////////////////////// struct call { template <typename T> call(T& t) { t(); } }; #endif /* Some ideas for static tools ... (c) Stefan Slapeta 2004 */ #include "static_tools.h" #include <boost/bind.hpp> #include <iostream> struct Test { void f() { std::cout << "called!" << std::endl; } }; int main() { static_<Test> s; s->f(); static_<Test>::get()->f(); Test t; static call c(boost::bind(Test::f, t)); }

Stefan Slapeta wrote:
Hi all,
there are 2 very small utilities I wrote a long time ago and that I use very often. I wonder if something like this has already been provided somewhere:
The first is a small class template static_ which create a singleton of a class "from outside".
Might it not be better named "singleton" Robert Ramey

Albeit this obviously does work with my compilers, I have to admit that I do not understand why. Can you please explain to me why template <typename T> T static_<T>::member; does not violate the ODR rule? If I do the very same with int aInt; in my header, the linker gives me a fatal "already defined" error. Thank you, Roland
participants (3)
-
Robert Ramey
-
Roland Schwarz
-
Stefan Slapeta