mardi 26 juillet 2016

How can I initialize static const class member object referring to private fields?

Here's the problem: a class called Factory has several non-static member functions of the same signature, let's call them f1, f2 and so on. I'd like to put pointers to these member functions in a std::vector that's a static const, as there's no need for that to ever change in runtime. Similarly, for reasons of elegance, I don't want to expose f1 and the others (summarily fi below), and not the vector either, but that's secondary.

Initializing the vector in class won't work because it's an incomplete type, and &Factory::fi are unknown at that time. Initializing it outside at file level won't work because fi are private and I can't befriend the global scope. Putting that in an initialization function and making that a friend won't work because that would require rewriting a const.

What works is:

  • removing the static const qualifiers, at the cost of making an unnecessary copy of this vector for each instance.

  • writing a static member function that declares a static variable and returns it. I thought this would be just as good but it makes my program run twice as slow with all optimizations on.

Surely, I would like to see a solution without the latter drawbacks. Please don't advise me to call the functions from a switch or similar vast changes of the paradigm.

Aucun commentaire:

Enregistrer un commentaire