I have a static array of pointers to functions as a member of a class.
I need to initialize it, but it turns out this array is 64K items long, so it's impractical to initialize it with a static initializer like { x, y, z, ... }
as it would clutter code.
I have instead to initialize it by code, with several loops.
The way I figured to do this is by initializing the static
array in the constructor and setting a flag to it, so only the construction of the first instance of the class would fire this initialization.
Also accessing this static flag from within instances would not be thread safe, but that's another story.
Is there a cleaner or better way of doing this?
I also would like this array to be const
, but I'm afraid the only way to do it is with the static {}
initialization, right?
Another option would be to use code generation: Write a separate program that generates the source code for the definition of the static array.
Maybe not the cleaniest code, but how about making the member array a static reference;
header file:
class MyClass
{
...
static const std::vector<pointer to member>& pointer_vector;
};
implementation file:
namespace
{
typedef std::vector<pointer to member> t_pointer_vector;
t_pointer_vector pointer_vector;
const t_pointer_vector& initialize_pointer_vector(void)
{
//generate pointer_vector
return pointer_vector;
}
}
t_pointer_vecotor& MyClass::pointer_vector = initialize_pointer_vector();
If you don't want std::vector
, you can take a look at std::tr1::array
, a fixed size array that is safer than and no less efficient than a C style array (according to Boost doc). It is a part of TR1. Basic info about TR1 can be found on wikipedia, its documentation under Boost.