0

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Petruza
  • 11,744
  • 25
  • 84
  • 136
  • 2
    64 _thousand_ functions? Also, how can you do this in a loop if every function has a name? – Seth Carnegie Nov 12 '11 at 23:23
  • 3
    Code generation, dude. Perl, python, whatever. – Nikolai Fetissov Nov 12 '11 at 23:25
  • 1
    I'm really interested in how you are going to _get_ all these function addresses without the very same clutter as with `{ &nitializer, &lists }`? AFAIK C++ doesn't have reflection? – sehe Nov 12 '11 at 23:26
  • @Nikolai yes you're right, I was thinking about doing it in a separate #included file – Petruza Nov 14 '11 at 13:17
  • @Seth no, the array has 64K items, and the type of the array is pointer to function, so they're 65536 pointers to functions. There are about 8 unique functions to which the array will point in an N to 1 relationship. – Petruza Nov 14 '11 at 13:18

2 Answers2

6

Another option would be to use code generation: Write a separate program that generates the source code for the definition of the static array.

celtschk
  • 19,311
  • 3
  • 39
  • 64
1

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.

Adam Trhon
  • 2,915
  • 1
  • 20
  • 51
  • thanks, but since it needs to be a fixed array of 65536 elements and direct random access so there's no need for a std::vector. – Petruza Nov 14 '11 at 13:21