That's tricky... Instead of initializing the structure in my (non-existent)
static constructor, we're creating a self-initializing structure. I like
it! Thanks!
So, as an academic question: Suppose I have an int variable that needs to
be initialized by passing its address to some routine. Is there some tricky
way to create a self-initializing static int variable?
- Bob
> That's tricky... Instead of initializing the structure in my
> (non-existent) static constructor, we're creating a self-initializing
> structure. I like it! Thanks!
That's the C++ way. The C# static constructor is a crutch to smooth over
one of the warts left by not having deterministic construction and
destruction - not to mention initialized static variables.
> So, as an academic question: Suppose I have an int variable that
> needs to be initialized by passing its address to some routine. Is
> there some tricky way to create a self-initializing static int
> variable?
Sure - just make a class to do it.
template <typename T, void (*fn)(T*)> struct init_t
{
init_t()
{
(*fn)(m_t);
}
operator T&
{
return m_t;
}
private:
T m_t;
};
// An initialization function
extern void some_init_fn(int* p);
// Helper typedef
typedef init_t<int,some_init_fn> InitInt;
// An int that's initialized by passing it's address to that function
InitInt my_initialized_int;
Again, one of a hundred different variations on a theme. If you truly want
the int to be an independent variable, then remove the private member and
pass it as a constructor parameter instead. Then you have to declared two
variables - one int and one init_t<int,void(*)(int*)>.
Boost (and various other template libraries) have pre-made portable,
reusable solutions to these problems and many more.
-cd
Bob Altman - 17 Oct 2007 18:13 GMT
Thanks Carl!
- Bob
>> That's tricky... Instead of initializing the structure in my
>> (non-existent) static constructor, we're creating a self-initializing
[quoted text clipped - 45 lines]
>
> -cd