0

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.

The Vee
  • 11,420
  • 5
  • 27
  • 60

1 Answers1

1

Is this what you have in mind? It wasn't quite clear from the problem statement.

#include <vector>

class Factory {
private:
    void f1() {}
    void f2() {}
public:
    typedef void (Factory::*PF)();
    static const std::vector<PF> v;
};

const std::vector<Factory::PF> Factory::v{&Factory::f1, &Factory::f2};


int main()
{
    Factory f;
    (f.*Factory::v[0])();
}

Demo

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • That's one of the approaches that I tried and didn't work (second case in second paragraph of the q). It says "Error: [signature...] Factory::f1() is private within this context". Well, it does not in *your* example. I'll need to find how that differs significantly from my current code. – The Vee Jul 26 '16 at 14:37
  • And sorry for being unclear, although I fail to see where. Your code is exactly the scenario I have in mind. Strangely this works alone (and is indeed one of the methods I tried first) but produces the above error when within my larger project. – The Vee Jul 26 '16 at 14:42
  • @TheVee Well, if you'd like further assistance, show [an MCVE](http://stackoverflow.com/help/mcve) that reproduces the failure. I can't help with code I can't see. – Igor Tandetnik Jul 26 '16 at 14:44
  • OMG, I forgot to call it `Factory::v` in the definition. And the compiler was happy about *that* because the class's `v` was then simply left an empty vector, but it thought I was trying to define a new const called `::v`, accessing the private fields. Thanks so much, your code (as a proof this is meant to work) helped me find this stupid error of mine! – The Vee Jul 26 '16 at 14:47