Boost logo

Boost :

Subject: Re: [boost] [static] A useful static variable generator.
From: herve martin (hervemart1_at_[hidden])
Date: 2009-03-20 03:46:36


Dongfei Yin wrote:

> Hi,
> Some time, the sequence of static variable initialization always make
> something bad.
> the piece of code below will useful about this problem.
>
> class static_
> {
> public:
> template <int N, class T>
> static T& var()
> {
> static T instance;
> return instance;
> }
>
> private:
> ~static_() {}
> };
>
> so, if a static variable of std::string is wanted, I will use:
>
> static_::var<0, std::string>() = ":)";
>
> the first template parameter is used for when many static variable of same
> type is needed.
> most important thing is all the variable will be initialized before use.
>
> Just for fun.
>
> Dongfei.
>

quite interesting trick for allocation of static variables !

we could also imagine:
 * storing the types list in a tuple to avoid passing type in var<>()
function
 * using enum rather than int as template parameter
it could give something like that:

class static_
{
public:
  enum static_names { my_string = 0, my_int, my_ptr };
  typedef boost::fusion::tuple< std::string, int, void*> static_types;

  template < static_names NAME >
  static typename boost::fusion::tuple_element<NAME,static_types>::type&
var()
  {
      static typename boost::fusion::tuple_element<NAME,static_types>::type
instance;
      return instance;
  }
};

static variable could be retrieved by:
    static_::var<static_::my_string>() = ":)";
    static_::var<static_::my_int>() = -1618;
    static_::var<static_::my_ptr>() = & static_::var<static_::my_string>();

    std::cout
        << " my_string: " << static_::var<static_::my_string>()
        << " my_int: " << static_::var<static_::my_int>()
        << " my_ptr: " << static_::var<static_::my_ptr>()
        << std::endl;

just need now to macro-ize the declaration to have something re-usable and
to manage cv qualifiers ...

thanks
herve


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