Boost logo

Boost :

From: Stefan Slapeta (stefan_at_[hidden])
Date: 2004-12-17 12:36:42


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));
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk